代码实现:
package thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @ClassName: ThreadCommunication
* @Description: 三个线程交替打印A,B,C
* @Author: xuezhouyi
* @Version: V1.0
**/
public class ThreadCommunication {
//线程标识
private Integer no = 0;
private Lock lock = new ReentrantLock();
//三个线程通信
Condition condition0 = lock.newCondition();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
/**
* 打印A
*/
public void printA() {
lock.lock();
try {
//非0线程则等待
if (no != 0) {
condition0.await();
}
//打印A
System.out.println(Thread.currentThread().getName() + ":A");
//唤醒1线程
no = 1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 打印B
*/
public void printB() {
lock.lock();
try {
//非1线程则等待
if (no != 1) {
condition1.await();
}
//打印B
System.out.println(Thread.currentThread().getName() + ":B");
//唤醒2线程
no = 2;
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 打印C
*/
public void printC() {
lock.lock();
try {
//非2线程则等待
if (no != 2) {
condition2.await();
}
//打印C
System.out.println(Thread.currentThread().getName() + ":C");
//唤醒0线程
no = 0;
condition0.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* Test
*/
private static class Test {
public static void main(String[] args) {
final ThreadCommunication tc = new ThreadCommunication();
final ExecutorService pool = Executors.newFixedThreadPool(3);
//启动三个线程测试
pool.submit(() -> {
for (int j = 0; j < 3; j++) {
tc.printA();
}
});
pool.submit(() -> {
for (int j = 0; j < 3; j++) {
tc.printB();
}
});
pool.submit(() -> {
for (int j = 0; j < 3; j++) {
tc.printC();
}
});
pool.shutdown();
}
}
}
运行结果:
pool-1-thread-1:A
pool-1-thread-2:B
pool-1-thread-3:C
pool-1-thread-1:A
pool-1-thread-2:B
pool-1-thread-3:C
pool-1-thread-1:A
pool-1-thread-2:B
pool-1-thread-3:C