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();
}
}
JDK并发包---(4)重入锁ReentrantLock:锁申请无限等待且不会产生死锁
原创
©著作权归作者所有:来自51CTO博客作者茜茜770的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:List转换成Map工具类
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
重入锁--ReentrantLock
优势:当许多线程都在争用同一个锁时,使用 ReentrantLock前加final
ReentrantLock 多线程 临界区 新特性 java -
ReentrantLock可重入锁
ReentrantLock可重入锁
公平锁 可重入 子程序 执行时间 并行执行