package com.zxl.thread.notify;
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;
public class ConditionThread implements Runnable { private ReentrantLock lock; private Condition c; private volatile int i=0; public ConditionThread(ReentrantLock lock){ this.lock = lock; c = lock.newCondition(); }
public void run() { lock.lock(); try{ while(true){ if(i==0){ System.out.println(Thread.currentThread().getName()+" will be waiting..."); c.await(); } System.out.println(Thread.currentThread().getName()+" is already waked up,i="+i); if(i>=1) return; } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ lock.unlock(); } } public Condition getCondition(){ return c; } public static void main(String[] args){ ReentrantLock lock = new ReentrantLock(); ConditionThread ct1 = new ConditionThread(lock); ConditionThread ct2 = new ConditionThread(lock); Thread t1 = new Thread(ct1); t1.setName("C_Thread_1"); Thread t2 = new Thread(ct2); t2.setName("C_Thread_2"); t1.start(); t2.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } lock.lock(); ct1.getCondition().signal(); //唤醒第一个线程 lock.unlock(); }
}