多线程实现打印ABC问题
需求:要求三个线程轮换打印ABC十次,每个每个线程打印一个字母
public class ABC_Object {
private Object lock = new Object();
int num = 0;
public void printABC(String name,int no){
for (int i = 0;i < 10;i++)
synchronized (lock){
while (num % 3 != no) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
++num;
System.out.println(name +" "+ no);
lock.notifyAll();
}
}
public static void main(String[] args) {
ABC_Object abc_object = new ABC_Object();
new Thread(() -> {
abc_object.printABC("A",0);
}).start();
new Thread(() -> {
abc_object.printABC("B",1);
}).start();
new Thread(() -> {
abc_object.printABC("C",2);
}).start();
}
}