线程的状态

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 main 方法 用户线程

gc垃圾回收 守护线程

 

 

 

 

 

 

 

 

 显示的加锁 ReentrantLock

将不安全的代码上锁 最好放在try代码块中 finally放入解锁语句

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

 

 

 

 

 

 

 

 

 

 

posted @ 2022-04-05 15:39  花心大萝卜li  阅读(22)  评论(0)    收藏  举报