多线程之间是抢占资源的,使用线程通信可以达到线程按序执行的目的
线程共享资源类, 首先创建一个资源类, 包含三个打印的方法以及首次打印的字符串
多个线程访问,方法加synchronized同步锁
class Resource {
String currentPrint = "AA"; // 初始打印,打印之后赋值为下一个要打印的内容
/**
* 打印AA
* @param next 下一个要打印的字符串
* @throws InterruptedException
*/
public synchronized void printAA(String next) throws InterruptedException {
// 不是要打印的内容, 阻塞线程
while (!Objects.equals(currentPrint, "AA")) {
wait();
}
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + ": AA");
}
currentPrint= next;
// 随机唤醒一个线程
notify();
}
/**
* 打印BB
* @param next 下一个要打印的字符串
* @throws InterruptedException
*/
public synchronized void printBB(String next) throws InterruptedException {
// 不是要打印的内容, 阻塞线程
while (!Objects.equals(currentPrint, "BB")) {
wait();
}
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + ": BB");
}
currentPrint= next;
// 随机唤醒一个线程
notify();
}
/**
* 打印CC
* @throws InterruptedException
*/