`

Condition

 
阅读更多

Condition

 

 Condition的功能类似在传统线程技术中的Object.wait()和Object.notify() 的功能。在等待Condition时,允许发生“虚假唤醒”,这通常作为对基础平台语义的让步。对于大多数应用程序,这带来的实际影响很小,因为Condition应该是在一个循环中被等待,并测试正被等待状态声明。某个实现可以随意移除可能的虚假唤醒,但建议应用程序程序员总是嘉定这些虚假唤醒可能发生,因此总是在一个循环中等待。

package com.ronbay.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionCmmunication {
	public static void main(String[] args) {
		final Business business = new Business();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					business.sub(i);
				}
			}
		}).start();
	}

	static class Business{
		Lock lock = new ReentrantLock();
		Condition condition = lock.newCondition();
		private boolean bShouldSub = true;
		public synchronized void sub(int i){
			lock.lock();
			try {
				while(!bShouldSub){
					try {
						condition.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				for (int j = 1; j < 10; j++) {
					System.out.println("sub thread sequence of " + j +",loop of =" + i);
				}
				bShouldSub = false;
				//发信号
				condition.signal();
			}finally{
				lock.unlock();
			}
		}
		public synchronized void main(int i) {
			lock.lock();
			try {
				while(bShouldSub){
					try {
						condition.await();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				for (int j = 1; j < 100; j++) {
					System.out.println("main thread sequence of " + j +",loop of =" + i);
				}
				bShouldSub = true;
				//发信号
				condition.signal();
			}finally{
				lock.unlock();
			}
		}
}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics