标签:exce 参考 语句 pre items lan style ant empty
Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set)。其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用。今天我们就通过实例来学习一个Condition的用法。
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class BoundedBuffer { final Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); final Condition notEmpty = lock.newCondition(); final String[] items = new String[10]; int putptr, takeptr, count; public void put(String x) throws InterruptedException { lock.lock(); try { while (count == items.length) notFull.await(); items[putptr] = x; if (++putptr == items.length) putptr = 0; ++count; notEmpty.signal(); } finally { lock.unlock(); } } public String take() throws InterruptedException { lock.lock(); try { while (count == 0) notEmpty.await(); String x = items[takeptr]; if (++takeptr == items.length) takeptr = 0; --count; notFull.signal(); return x; } finally { lock.unlock(); } } }
public class ConditionTest1 { public static void main(String[] args) throws Exception { final BoundedBuffer boundedBuffer = new BoundedBuffer(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { try { boundedBuffer.take(); System.out.print("t" + i + " "); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { try { boundedBuffer.put("string" + i); System.out.print("p" + i + " "); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }
运行的结果如下:不固定
p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 t0 p10 t1 p11 t2 p12 t3 p13 t4 p14 t5 p15 t6 p16 t7 p17 t8 p18 t9 p19 t10 t11 t12 t13 t14 t15 t16 t17 t18 t19
java高级---->Thread之Condition的使用
标签:exce 参考 语句 pre items lan style ant empty
原文地址:http://www.cnblogs.com/huhx/p/baseusejavaCondition.html