rzkwz
//測試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();
            }
        }
    }
}

 

分类:

技术点:

相关文章:

  • 2021-04-15
  • 2022-01-07
  • 2021-12-12
  • 2021-07-20
  • 2021-10-19
  • 2021-04-10
  • 2021-11-17
  • 2020-11-12
猜你喜欢
  • 2021-10-16
  • 2021-12-20
  • 2021-07-31
  • 2022-02-18
  • 2021-09-06
  • 2021-04-13
  • 2021-01-12
相关资源
相似解决方案