lock加锁

package com.cj;

import java.util.concurrent.locks.ReentrantLock;

public class LockTest implements Runnable{
    private static int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();

    public void run() {
        while (true){
            try {
                lock.lock();
                if(ticket>0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖票:"+"票号:"+ticket);
                    ticket--;
                }else{
                    break;
                }
            }finally {
                lock.unlock();
            }

        }
    }
}
class Test4{
    public static void main(String[] args) {
        LockTest lock = new LockTest();
        Thread w1 = new Thread(lock);
        Thread w2 = new Thread(lock);
        Thread w3 = new Thread(lock);

        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");
        w1.start();
        w2.start();
        w3.start();
    }
}

 

posted @ 2022-04-02 17:59  写代码的小哥哥  阅读(99)  评论(0)    收藏  举报