我正在学习Java并发并尝试ReentrantLock类方法。在尝试 tryLock() 方法并运行示例程序时,它没有按预期工作。根据定义,如果锁可用,则 tryLock() 返回 true,线程将获得锁,如果不可用,则返回 false。
所以在我的代码中,我有两个线程,如果 t1 获得锁定,那么它将执行 if 部分操作,t2 将执行 else 操作。我错过了什么吗?请帮忙。
代码:
import java.util.concurrent.locks.ReentrantLock;
class ReentrantLockMethods extends Thread{
ReentrantLock l = new ReentrantLock();
public ReentrantLockMethods(String name) {
super(name);
}
public void run() {
if(l.tryLock()) {
System.out.println(Thread.currentThread().getName()+"....got Lock and performing safe operations");
try {
Thread.sleep(5000);
}
catch(InterruptedException e) {}
l.unlock();
}
else {
System.out.println(Thread.currentThread().getName()+ "....unable to get Lock hence, performing alternate operations");
}
}
}
public class ReentrantLockDemo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ReentrantLockMethods t1 = new ReentrantLockMethods("First Thread");
ReentrantLockMethods t2 = new ReentrantLockMethods("Second Thread");
t1.start();
t2.start();
}
}
实际产量:
First Thread....got Lock and performing safe operations
Second Thread....got Lock and performing safe operations
预期输出:
First Thread....got Lock and performing safe operations
Second Thread....unable to get Lock hence, performing alternate operations
或
Second Thread....got Lock and performing safe operations
First Thread....unable to get Lock hence, performing alternate operations
在您的
ReentrantLockMethods
实现中,每个实例都有自己的锁,因此不存在争用,并且两者都可以取出锁。如果您想观察所需的行为,您需要确保两个线程使用相同的锁。
顺便说一句,通常您不应该扩展
Thread
,而应该实现 Runnable
。