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(); } }
相关文章推荐
- JDK并发包---(3)重入锁ReentrantLock:锁申请等待限时
- JDK并发包---(2)重入锁ReentrantLock:中断响应
- JDK并发包---(5)重入锁ReentrantLock:公平锁
- JDK并发包---(6)重入锁ReentrantLock搭档:Condition条件
- java高并发程序设计总结三:JDK并发包之ReentrantLock重入锁
- JDK并发包---(1)重入锁ReentrantLock:基本使用
- 【Java并发】- ReentrantLock,重入锁
- Java并发——重入锁ReentrantLock的实现原理及源码解析
- 【死磕Java并发】-----J.U.C之重入锁:ReentrantLock
- 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
- java并发-锁-ReentrantLock(重入锁)和ReentrantReadWriteLock(读写锁)
- 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
- Java高并发程序-Chapter3 JDK并发包(第九讲)同步控制之 ReentrantLock 重用锁
- 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
- 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
- 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
- JDK并发包---(8)ReadWriteLock读写锁:替换ReentrantLock,提高性能
- 【死磕Java并发】—– J.U.C之重入锁:ReentrantLock
- JDK 5.0 Concurrency Utilities 并发处理 ReentrantLock 可重入锁
- jdk源码解读-并发包-Lock-ReentrantLock(1)--lock()与unlock()方法走读