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然后加入到等待队列中也就是说你这个锁加的没啥意义

    评论

报告相同问题?

悬赏问题

  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿