Condition 线程通信

  在jdk1.5以后,我们可以用Lock,Condition 进行线程通信。

  还是消费者生产者案例。

 

在Clerk中:

class Clerk2 {
	private int product = 0;

	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	// 进货
	public void get() {
		lock.lock();

		try {
			if (product >= 1) { // 为了避免虚假唤醒,应该总是使用在循环中。
				System.out.println("产品已满!");

				try {
					condition.await();
				} catch (InterruptedException e) {
				}

			}
			System.out.println(Thread.currentThread().getName() + " : "
					+ ++product);

			condition.signalAll();
		} finally {
			lock.unlock();
		}

	}

	// 卖货
	public void sale() {
		lock.lock();

		try {
			if (product <= 0) {
				System.out.println("缺货!");

				try {
					condition.await();
				} catch (InterruptedException e) {
				}
			}

			System.out.println(Thread.currentThread().getName() + " : "
					+ --product);

			condition.signalAll();

		} finally {
			lock.unlock();
		}
	}
}

  Condition 与 object 的对应:

 

Object方法   Condition方法
this.wait(); condition.await();
this.notify(); condition.signal();
this.notifyAll(); condition.signalAll();

 

posted @ 2017-11-02 14:50  myJavaCareerLife  阅读(79)  评论(0)    收藏  举报