1.使用线程实现:两个线程循环打印AB
public class PrintAB {
/**
* 上一次打印为A则为true,否则为false
*/
private static volatile boolean flag = false;
public static void main(String[] args) {
PrintAB printAB = new PrintAB();
// 1.循环打印AB
new Thread(() -> printAB.printA()).start();
new Thread(() -> printAB.printB()).start();
}
private synchronized void printA() {
while(true) {
// true表示上一次打印为A
if(flag) {
try {
// 当前线程等待
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print("A");
// 打印A之后需置换标识为true,表示上一次打印为A
flag = true;
notifyAll();
}
}
private synchronized void printB() {
while(true) {
// 上一次打印不为A,即为B
if(!flag) {
try {
// 当前线程等待
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print("B");
// 打印B之后需置换标识为false,表示上一次打印为B
flag = false;
notifyAll();
}
}
}
2.使用线程实现:两个线程循环打印AB 10次
public class PrintAB {
/**
* 上一次打印为A则为true,否则为false
*/
private static volatile boolean flag = false;
public static void main(String[] args) {
PrintAB printAB = new PrintAB();
// 2.循环打印AB 10次
new Thread(() -> printAB.printA2(10)).start();
new Thread(() -> printAB.printB2(10)).start();
}
private synchronized void printA2(int N) {
int count = 0;
while(count < N) {
// true表示上一次打印为A
if(flag) {
try {
// 当前线程等待
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print("A");
count += 1;
// 打印A之后需置换标识为true,表示上一次打印为A
flag = true;
notifyAll();
}
}
private synchronized void printB2(int N) {
int count = 0;
while(count < N) {
// 上一次打印不为A,即为B
if(!flag) {
try {
// 当前线程等待
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.print("B");
count += 1;
// 打印B之后需置换标识为false,表示上一次打印为B
flag = false;
notifyAll();
}
}
}
原文:https://www.cnblogs.com/kingsonfu/p/15104800.html