zoukankan      html  css  js  c++  java
  • Lock锁

    //測試lock鎖
    public class TestLock {
        public static void main(String[] args) {
            TestLock2 testLock2 = new TestLock2();
            new Thread(testLock2).start();
            new Thread(testLock2).start();
            new Thread(testLock2).start();
        }
    }
    class TestLock2 implements  Runnable{
        int ticketNums = 10;
    
        //定義lock
        private final ReentrantLock lock= new ReentrantLock();
    
        @Override
        public void run(){
            while(true){
                try{
                lock.lock();//枷鎖
                    if (ticketNums>0){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(ticketNums--);
                    }else{
                        break;
                    }
                }finally{
                    //解鎖
                    lock.unlock();
                }
            }
        }
    }
  • 相关阅读:
    6月17日
    6月16日
    6月15日
    6月14日
    6月13日
    6月12日
    6月11日
    6月10日
    6月8日
    6月5日
  • 原文地址:https://www.cnblogs.com/rzkwz/p/12488456.html
Copyright © 2011-2022 走看看