使用Condition实现等待/通知:
1 import java.util.concurrent.locks.Condition; 2 import java.util.concurrent.locks.Lock; 3 import java.util.concurrent.locks.ReentrantLock; 4 5 6 public class MyService { 7 8 private Lock lock = new ReentrantLock(); 9 private Condition condition = lock.newCondition(); 10 11 public void await() { 12 try { 13 lock.lock();//上锁 14 System.out.println("await时间为:" + System.currentTimeMillis()); 15 condition.await(); 16 } catch (InterruptedException e) { 17 e.printStackTrace(); 18 }finally { 19 lock.unlock(); 20 } 21 } 22 23 public void signal() { 24 try { 25 lock.lock(); 26 System.out.println("signal时间为:" + System.currentTimeMillis()); 27 condition.signal();
System.out.println("我被唤醒了"); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 }finally { 31 lock.unlock(); 32 } 33 } 34 }
1 public class ThreadA extends Thread{ 2 3 private MyService service; 4 5 public ThreadA(MyService service) { 6 this.service = service; 7 } 8 9 @Override 10 public void run() { 11 service.await(); 12 } 13 }
1 /** 2 * 测试类 3 */ 4 public class Run { 5 6 /** 7 * Object类中的wait() 相当于Condition类中的await() 8 * Object类中的wait(long timeout) 相当于Condition类中的await(long time,TimeUnit unit) 9 * Object类中的notify() 相当于Condition类中的signal() 10 * Object类中的notifyAll() 相当于Condition类中的signalAll() 11 */ 12 public static void main(String[] args) { 13 MyService service = new MyService(); 14 15 ThreadA a = new ThreadA(service); 16 a.start(); 17 try { 18 Thread.sleep(3000); 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 service.signal(); 23 } 24 }
运行结果如下: