package thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用多个Condition线程通信
* 第一个线程循环10,第二个线程循环10次,第三个线程循环10次,如此循环100次
*/
public class ThreeConditionDemo
{
public static void main(String[] args)
{
final Business business = new Business();
new Thread(new Runnable()
{
public void run()
{
for (int i = 0; i < 100; i++)
{
business.sub1(i);
}
}
}).start();
new Thread(new Runnable()
{
public void run()
{
for (int i = 0; i < 100; i++)
{
business.sub2(i);
}
}
}).start();
new Thread(new Runnable()
{
public void run()
{
for (int i = 0; i < 100; i++)
{
business.sub3(i);
}
}
}).start();
}
static class Business
{
private int shouldSub = 1;
final Lock lock = new ReentrantLock();
final Condition conditionSub1 = lock.newCondition();
final Condition conditionSub2 = lock.newCondition();
final Condition conditionSub3 = lock.newCondition();
public void sub1(int i)
{
lock.lock();
try
{
while (shouldSub != 1)
{
try
{
conditionSub1.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++)
{
System.out.println("sub1 thread " + j);
}
shouldSub = 2;
conditionSub2.signal();
}
finally
{
lock.unlock();
}
}
public void sub2(int i)
{
lock.lock();
try
{
while (shouldSub != 2)
{
try
{
conditionSub2.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++)
{
System.out.println("sub2 thread " + j);
}
shouldSub = 3;
conditionSub3.signal();
}
finally
{
lock.unlock();
}
}
public void sub3(int i)
{
lock.lock();
try
{
while (shouldSub != 3)
{
try
{
conditionSub3.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
for (int j = 0; j < 10; j++)
{
System.out.println("sub3 thread " + j);
}
shouldSub = 1;
conditionSub1.signal();
}
finally
{
lock.unlock();
}
}
}
}
运行结果如下:
sub1 thread 0
sub1 thread 1
sub1 thread 2
sub1 thread 3
sub1 thread 4
sub1 thread 5
sub1 thread 6
sub1 thread 7
sub1 thread 8
sub1 thread 9
sub2 thread 0
sub2 thread 1
sub2 thread 2
sub2 thread 3
sub2 thread 4
sub2 thread 5
sub2 thread 6
sub2 thread 7
sub2 thread 8
sub2 thread 9
sub3 thread 0
sub3 thread 1
sub3 thread 2
sub3 thread 3
sub3 thread 4
sub3 thread 5
sub3 thread 6
sub3 thread 7
sub3 thread 8
sub3 thread 9
sub1 thread 0
sub1 thread 1
sub1 thread 2
sub1 thread 3
......