zoukankan      html  css  js  c++  java
  • Java并发Semaphore信号量的学习

    public class MyThreadTest {
        private final static Semaphore semaphore = new Semaphore(2);// 设置2个车位
     
        public static void main(String[] args) {
            System.out.println("start");
     
            p(semaphore, true, 1);
            p(semaphore, false, 2);
            p(semaphore, false, 3);
            p(semaphore, true, 4);
            p(semaphore, true, 5);
     
            System.out.println("end");
        }
     
        /**
         * 停车
         *
         * @param semaphore 信号对象
         * @param enterInto 停车true/出库false
         * @param theCarNum 车辆序号
         */
        private static void p(Semaphore semaphore, boolean enterInto, int theCarNum) {
            if (!enterInto) {
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("车辆出库");
     
                // 释放1个车位
                // 通过LockSupport.unpark(s.thread)来释放锁,详见AbstractOwnableSynchronizer.unparkSuccessor
                semaphore.release(1);
            }
            try {
                // 如果达到设定的信号量,通过LockSupport.park(this)来释放锁,详见AbstractOwnableSynchronizer.parkAndCheckInterrupt
                semaphore.acquire();
                System.out.println("第 " + theCarNum + " 辆车进入");
            } catch (Exception e) {
                e.printStackTrace();
            }
     
        }
     
        /**
         *     Semaphore中Sync继承了AbstractQueuedSynchronizer
         *     改变AbstractOwnableSynchronizer中state值(该值记录着剩余信号量)
         *
         *     AbstractOwnableSynchronizer加载时会调用静态代码块获取state的偏移地址:
         *     stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
         *     上述获取对象某个变量的效率比使用反射获取的效率高
         *
         *     protected final boolean compareAndSetState(int expect, int update) {
         *          // stateOffset为state变量的偏移地址
         *         return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
         *     }
         */
     
    }
    

      

    原文:https://blog.csdn.net/qq_35001776/article/details/89158734

  • 相关阅读:
    ACM HDU 1176 免费馅饼(DP)
    PHP下载时中文文件名乱码的问题
    NYOJ 27
    NYOJ 148
    NYOJ 8
    NYOJ 138
    NYOJ 461
    POJ 1200
    STL排序算法
    NYOJ 523
  • 原文地址:https://www.cnblogs.com/qbdj/p/10869946.html
Copyright © 2011-2022 走看看