gpt4 book ai didi

java - ReentrantLock 未显示预期结果

转载 作者:行者123 更新时间:2023-12-01 07:46:53 26 4
gpt4 key购买 nike

问题出在哪里? ReentrantLock 未显示预期结果。两个线程同时执行,而不是等待一个线程。

class MyThread2 extends Thread{
String name;
ReentrantLock reentrantLock = new ReentrantLock();
MyThread2(String name){
this.name = name;
}
public void run(){
do {
try {
if (reentrantLock.tryLock(20,TimeUnit.MILLISECONDS)){
System.out.println("executing : "+ name);
Thread.sleep(500);
reentrantLock.unlock();
break;
}else {
System.out.println("waiting "+ name);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}while (true);
}
}

public class LockDemo2{
public static void main(String[] args) {
new MyThread2("Thread - 1").start();
new MyThread2("Thread - 2").start();
}
}

输出:

executing : Thread - 1
executing : Thread - 2

最佳答案

您应该在不同的线程中使用相同的ReentrantLock,而不是创建不同的锁。

将构造函数更改为:

ReentrantLock reentrantLock;
MyThread2(String name, ReentrantLock lock){
this.name = name;
this.reentrantLock = lock;
}

并将相同的锁传递给他们:

ReentrantLock lock = new ReentrantLock();
new MyThread2("Thread - 1", lock).start();
new MyThread2("Thread - 2", lock).start();

关于java - ReentrantLock 未显示预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50077978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com