/**
* Java 3个线程依次打印ABC,并且循环10次
*
* @author http://blog.csdn.net/qq2439169750
*/
public class ABCThread {
public static void main(String[] args) {
new Thread(new Printer(" A", 0)).start();
new Thread(new Printer(" B", 1)).start();
new Thread(new Printer("C", 2)).start();
}
}
class Printer implements Runnable {
private static int flag = 0;// 控制该哪个线程打印
private String str;// 要打印的字符
private int id;
public Printer(String _str, int _id) {
str = _str;
id = _id;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (Printer.class) {// 同一时刻只有一个Printer的实例执行
while (flag % 3 != id) {
try {
Printer.class.wait();// 注意是Printer.class
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(str);
flag++;
/*
* Note that the call to notifyAll does not immediately activate
* a waiting thread. It only unblocks the waiting threads so
* that they can compete for entry into the object after the
* current thread has exited the synchronized method.
* ------《CoreJava》多线程
*/
// 即当前线程退出同步块之后,其他线程就会被唤醒
Printer.class.notifyAll();
}
}
}
}
Java 3个线程依次打印ABC,并且循环10次
最新推荐文章于 2024-08-12 00:17:43 发布