java多线程之线程间通信

package com.weeya.nine;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author skyarac
* 三个线程 老大唤醒老二,老二唤醒老三,老三唤醒老大
* 2013年12月16日
*/
public class ThreeConditionCommunication {
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.main(i);
}
}
}).start();
new Thread(new Runnable() { //老二线程
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
business.sub2(i);
}
}
}).start();
new Thread(new Runnable() {  //老三线程
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
business.sub3(i);
}
}
}).start();
}
}
class Business {
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int shouldSub = 1;
/*
* @param i 老大
*/
public void main(int i) {
lock.lock();
while (shouldSub != 1) { // 这里可以使用if循环
try {
condition1.await();// 主线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("老大 sequence of " + j + ",loop of " + i);
}
shouldSub = 2;
condition2.signal();
lock.unlock();
}
/*
* @param i 老二
*/
public void sub2(int i) {
lock.lock();
while (shouldSub != 2) { // 这里可以使用if循环
try {
condition2.await(); // 子线程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("老二 sequence of " + j + ",loop of " + i);
}
shouldSub = 3;
condition3.signal();
lock.unlock();
}
/*
* @param i 老三
*/
public void sub3(int i) {
lock.lock();
while (shouldSub != 3) { // 这里可以使用if循环
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("老三 sequence of " + j + ",loop of " + i);
}
shouldSub = 1;
condition1.signal();
lock.unlock();
}
}
 

 

你可能感兴趣的:(java,多线程,通信,import)