death05 2019-09-25 18:39 采纳率: 16.7%
浏览 758

Java中的ReentrantLock的lock()方法是否能让线程进入BLOCKING状态

代码如下:

/**
 * 自定义线程类
 */
public class MyThread extends Thread{

    private static final ReentrantLock LOCK = new ReentrantLock();

    private static final Condition condition = LOCK.newCondition();

    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run(){
        LOCK.lock();
        try {
            System.out.println(super.getName() + " exe");
            while (true) {
                try {
                    condition.await(1, TimeUnit.SECONDS);
                    System.out.println(super.getName() + " await finish");
                } catch (InterruptedException e) {
                    System.out.println(super.getName() + " interrupt");
                    System.out.println(this.getState());
                }
            }
        } finally {
            LOCK.unlock();
            System.out.println(super.getName() + " unlock");
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new MyThread("thread1");
        thread1.start();

        Thread thread2 = new MyThread("thread2");
        thread2.start();

        Thread thread3 = new MyThread("thread3");
        thread3.start();
    }
}

结果如下:

thread1 exe
thread2 exe
thread3 exe
thread1 await finish
thread3 await finish
thread2 await finish
thread3 await finish
thread1 await finish
thread2 await finish

我最初设想的是,三个线程抢LOCK锁,只有1个线程抢到,其他两个线程处于阻塞状态。

但从结果来看,三个线程都抢到了,请问这是为什么呢?

  • 写回答

3条回答 默认 最新

  • 奋斗的小杨 2019-09-25 19:42
    关注

    condition.await()方法后,会使得当前线程释放lock然后加入到等待队列中也就是说你这个锁加的没啥意义

    评论

报告相同问题?