import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Lock下提供了一个condition条件,其中的condition提供了await和signal两个方法, * 起作用和Object提供的wait和notify相同,一个lock下可以有多个condition。 * * @author * * 例子,使用lock实现互斥,condition实现通信,来做子线程打印10次,主线程打印100次,如此反复 */ public class ConditionTest { public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable() { @Override public void run() { while (true) { business.sub(); } } }).start(); while (true) { business.main(); } } // ConditionTest.Business static class Business { private Lock lock = new ReentrantLock(); private Condition cond = lock.newCondition(); private boolean flag = true; // true : main run , false : sub run public void main() { lock.lock(); try { while (!flag) { try { cond.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 100; i++) { System.out.println("main of loop Number " + i); } flag = false; cond.signal(); } finally { lock.unlock(); } } public void sub() { lock.lock(); try { while (flag) { try { cond.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 10; i++) { System.out.println("sub of loop Number" + i); } flag = true; cond.signal(); } finally { lock.unlock(); } } } }