我正在学习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