重入锁(ReentrantLock)是一种递归无阻塞的同步机制,一个可重入的互斥锁定 Lock,它具有与使用 synchronized 方法和语句所访问的隐式监视器锁定相同的一些基本行为和语义,但功能更强大。
在Condition中,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll(),传统线程的通信方式,Condition都可以实现,这里注意,Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法。
Condition的强大之处在于它可以为多个线程间建立不同的Condition。
例子:接着synchronized的题目,改用ReentrantLock实现
public class TestLock implements Runnable { private int num; private int initNum; private Lock lock; private Condition thisCondtion; public TestLock(Lock lock, Condition thisCondtion, int num, int initNum) { this.lock = lock; this.thisCondtion = thisCondtion; this.num = num; this.initNum = initNum; } @Override public void run() { for (int i = 0; i < 6; i++) { try { lock.lock(); while (initNum < num) { thisCondtion.signal(); System.out.println(Thread.currentThread().getName() + ":" + initNum); initNum++; try { thisCondtion.await(); } catch (InterruptedException e1) { e1.printStackTrace(); } } } finally { lock.unlock(); } } } public static void main(String[] args) { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); TestLock testLock = new TestLock(lock, condition, 51, 1); Thread thread1 = new Thread(testLock, "线程1"); Thread thread2 = new Thread(testLock, "线程2"); thread1.start(); try { thread1.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } thread2.start(); } }