public class TryLock implements Runnable{
public static ReentrantLock lock1 = new ReentrantLock();
public static ReentrantLock lock2 = new ReentrantLock();
int lock;
public TryLock(int lock){
this.lock = lock;
}
@Override
public void run() {
if(lock == 1){
while(true) {
if(lock1.tryLock()){
try{
try{
Thread.sleep(500);
} catch (InterruptedException e){
}
if(lock2.tryLock()){
try{
System.out.println(Thread.currentThread().getId()+ ":My Job done");
return;
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
}
}else{
while(true) {
if(lock2.tryLock()){
try{
try{
Thread.sleep(500);
} catch (InterruptedException e){
}
if(lock1.tryLock()){
try{
System.out.println(Thread.currentThread().getId()+ ":My Job done");
return;
} finally {
lock1.unlock();
}
}
} finally {
lock2.unlock();
}
}
}
}
}
}
public static void main(String[] args) {
TryLock tryLock1 = new TryLock(1);
TryLock tryLock2 = new TryLock(2);
Thread t1 = new Thread(tryLock1);
Thread t2 = new Thread(tryLock2);
t1.start();
t2.start();
System.out.println("Hello world!");
}
上述代码采用了非常容易死锁的加锁顺序,
先让t1获得lock1,再让t2获得lock2,接着反向请求,
让t1申请loc2,t2申请lock1.在一般情况下,这会导致t1和t2相互等待
从而引起死锁。但是使用tryLock()方法后,这种情况就大大改善。
由于线程不会傻傻地等待,而是不停地尝试,因此,只要执行足够长的时间,
线程总是会得到所需要的资源。从而正常执行。
(这里以线程同时获得lock1和lock2两把锁,作为其可以正常执行的条件)。
在同时获得lock1和lock2后,线程就打印出标志着任务完成的信息"My Job done"。