Condition接口的await()、signal()
Condition是在java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition1的await()、signal()这种方式实现线程间协作更加安全和高效。因此通常来说比较推荐使用Condition,阻塞队列实际上是使用了Condition来模拟线程间协作。
Condition是个接口,基本的方法就是await()和signal()方法;
Condition的创建:
Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition()
调用Condition的await()、signal()、signalAll()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用
Condition condition = lock.newCondition();
condition.await(); 类似wait
Condition. Signal() 类似notify
例子:
class Res { public String userName; public String sex; public boolean flag = false; Lock lock = new ReentrantLock(); } class InputThread extends Thread { private Res res; Condition newCondition; public InputThread(Res res, Condition newCondition) { this.res = res; this.newCondition=newCondition; } @Override public void run() { int count = 0; while (true) { // synchronized (res) { try { res.lock.lock(); if (res.flag) { try { // res.wait(); newCondition.await(); } catch (Exception e) { // TODO: handle exception } } if (count == 0) { res.userName = "小强"; res.sex = "男"; } else { res.userName = "小红"; res.sex = "女"; } count = (count + 1) % 2; res.flag = true; // res.notify(); newCondition.signal(); } catch (Exception e) { // TODO: handle exception }finally { res.lock.unlock(); } } // } } } class OutThrad extends Thread { private Res res; private Condition newCondition; public OutThrad(Res res,Condition newCondition) { this.res = res; this.newCondition=newCondition; } @Override public void run() { while (true) { // synchronized (res) { try { res.lock.lock(); if (!res.flag) { try { // res.wait(); newCondition.await(); } catch (Exception e) { // TODO: handle exception } } System.out.println(res.userName + "," + res.sex); res.flag = false; // res.notify(); newCondition.signal(); } catch (Exception e) { // TODO: handle exception }finally { res.lock.unlock(); } // } } } } public class ThreadDemo01 { public static void main(String[] args) { Res res = new Res(); Condition newCondition = res.lock.newCondition(); InputThread inputThread = new InputThread(res,newCondition); OutThrad outThrad = new OutThrad(res,newCondition); inputThread.start(); outThrad.start(); } }

浙公网安备 33010602011771号