package conditionTest9;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 在Condition中,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll(),
* 传统线程的通信方式,Condition都可以实现。Condition的强大之处在于它可以为多个线程间建立不同的Condition
*
*/
public class ThreadTest2 {
public static void main(String[] args) {
final Business business = new Business();
//1、子线程执行10次for循环,bool = false进入线程等待状态,开始执行主线程
//2、主线程执行100次循环,bool = true进入线程等待状态,唤醒子线程
//3、持续100次
new Thread(new Runnable() {
@Override
public void run() {
threadExecute(business, "sub");
}
}).start();
threadExecute(business, "main");
}
public static void threadExecute(Business business, String threadType) {
for(int i = 0; i < 100; i++) {
try {
if("main".equals(threadType)) {
business.main(i);
} else {
business.sub(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Business {
private boolean bool = true;
private Lock lock = new ReentrantLock();
//Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法
private Condition condition = lock.newCondition();
public /*synchronized*/ void main(int loop) throws InterruptedException {
lock.lock();
try {
while(bool) {
condition.await();//this.wait();
}
for(int i = 0; i < 100; i++) {
System.out.println("main thread seq of " + i + ", loop of " + loop);
}
bool = true;
condition.signal();//this.notify();
} finally {
lock.unlock();
}
}
public /*synchronized*/ void sub(int loop) throws InterruptedException {
lock.lock();
try {
while(!bool) {
condition.await();//this.wait();,线程等待
}
for(int i = 0; i < 10; i++) {
System.out.println("sub thread seq of " + i + ", loop of " + loop);
}
bool = false;
condition.signal();//this.notify(); //唤醒阻塞队列的某线程到就绪队列
} finally {
lock.unlock();
}
}
}
本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/7481142,转载请注明。
网友评论