[Java] 纯文本查看 复制代码
public class ThreeConditionCommunication2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Business bus=new ThreeConditionCommunication2().new Business();
new Thread(
new Runnable(){
@Override
public void run() {
for (int j = 0; j < 5; j++) {
bus.sub2(j);
}
}
}
).start();
new Thread(
new Runnable(){
@Override
public void run() {
for (int j = 0; j < 5; j++) {
bus.sub3(j);
}
}
}
).start();
for (int j = 0; j < 5; j++) {
bus.sub1(j);
}
}
//主要是这里不同
class Business{
Lock lock=new ReentrantLock();
Condition con1=lock.newCondition(); // 1 - 2 通信
Condition con2=lock.newCondition(); // 2 - 3 通信
int step=1;
public void sub1(int i){
lock.lock();
try {
while(step!=1)
con1.await();
for (int j = 0; j < 100; j++) {
System.out.println("main thread sequence of "+j+" loop of"+i);
}
step=2;
con1.signal();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void sub2(int i){
lock.lock();
try {
while(step!=2)
con1.await();
for (int j = 0; j < 10; j++) {
System.out.println("Sub2 thread sequence of "+j+" loop of"+i);
}
step=3;
con2.signal();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void sub3(int i){
lock.lock();
try {
while(step!=3)
con2.await();
for (int j = 0; j < 20; j++) {
System.out.println("Sub3 thread sequence of "+j+" loop of"+i);
}
step=1;
con1.signal();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
}