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

  • 相关阅读:
    二叉搜索树的平衡--AVL树和树的旋转
    nginx+keepalived高可用及双主模式
    date,datetime的对比
    reg007最新邀请码!!!
    1292
    bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?
    JS数组实际应用方法整理
    CSS3动画常用贝塞尔曲线-效果演示
    vue-cli3 配置生产-测试环境
    vue 路由知识点梳理及应用场景整理
  • 原文地址:https://www.cnblogs.com/qbdj/p/10869946.html
Copyright © 2011-2022 走看看