您的位置:首页 > 编程语言 > Java开发

JDK并发包---(4)重入锁ReentrantLock:锁申请无限等待且不会产生死锁

2017-01-04 15:49 525 查看
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

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() {
System.out.println(Thread.currentThread().getId() + ":Start Date:"+new Date());
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");
System.out.println(Thread.currentThread().getId() + ":End Date:"+new Date());
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");
System.out.println(Thread.currentThread().getId() + ":End Date:"+new Date());
return;
} finally {
lock1.unlock();
}
}
} finally {
lock2.unlock();
}
}
}

}

}

public static void main(String args[]) {
TryLock r1 = new TryLock(1);
TryLock r2 = new TryLock(2);

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

t1.start();
t2.start();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: