import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程通信(子线程运行10次,主线程运行100次,如此循环50次)[用condition替代wait,notify等待和唤醒操作]
* @author 谭飞
* @date 2012-02-02
*/
public class ConditionThreadCommunication {
/**
* @param args
*/
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();
/*主线程*/
for(int i = 1; i <= 50; i++)
{
business.main(i);
}
}
static class Business {//处理线程安全归为一类,这样用的就是同一把同步锁
private boolean subShouldRun = true; //当为true时子线程执行,当为false时主线程执行
private Lock lock = new ReentrantLock();//创建一把锁
private Condition condition = lock.newCondition();//创建condition操作等待与唤醒操作
public void sub(int i)
{
lock.lock();//打开锁
try
{
while(!subShouldRun)
{
try {
//this.wait();//等待线程
condition.await();//condition等待
} catch (Exception e) {
e.printStackTrace();
}
}
for(int j = 1; j <= 10; j++)
{
System.out.println("sub Thread sequence of " + j + ", loop of " + i);
}
subShouldRun = false;
//this.notify();//唤醒线程
condition.signal();//condition唤醒线程
}finally
{
lock.unlock();//关闭锁
}
}
public void main(int i)
{
lock.lock();//打开锁
try
{
while(subShouldRun)
{
try {
//this.wait();
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);
}
subShouldRun = true;
//this.notify();
condition.signal();
}finally
{
lock.unlock();//关闭锁
}
}
}
}
线程通信(子线程运行10次,主线程运行100次,如此循环50次)[用condition替代wait,notify等待和唤醒操作]
最新推荐文章于 2020-06-01 09:14:24 发布