滨海之君
2021-02-19 14:21
采纳率: 60%
浏览 358
已采纳

多线程加lock锁后为什么每次执行的都是同一个线程

//这个多线程加上lock锁后为什么只有线程a在执行???
public class LockTest {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2,"a").start();
        new Thread(testLock2,"b").start();
        new Thread(testLock2,"c").start();
    }
}
//多线程对象
class TestLock2 implements Runnable{
    int ticketNums = 10;
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if(ticketNums > 0){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                    System.out.println(Thread.currentThread().getName());
                }else {
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}

下面是控制台的输出: 

6条回答 默认 最新

相关推荐 更多相似问题