Lock锁

package testLock;

import java.util.concurrent.locks.ReentrantLock;

public class demo01  {
    public static void main(String[] args) {
        demo02 d= new demo02();
        new Thread(d).start();
        new Thread(d).start();
        new Thread(d).start();
    }


}
class demo02 implements Runnable{

    int tickets=10;
    //定义lock锁
    private final ReentrantLock lock=new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if(tickets>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(tickets--);
                }else{
                    break;
                }
            }finally {
                lock.unlock();
            }


        }
    }
}

 

posted @ 2020-10-14 17:28  IanW  阅读(70)  评论(0编辑  收藏  举报