public class MyThread extends Thread{
private static Object o = new Object();
private static int count = 0;
private char ID;
private int id;
private int num = 0;
public MyThread(int id, char ID) {
this.id = id;
this.ID = ID;
}
public void run() {
synchronized (o) {
while (num < 10) {
if (count % 3 == id) {
System.out.print(ID);
++count;
++num;
o.notifyAll();
}
else {
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
(new MyThread(0, 'A')).start();
(new MyThread(1, 'B')).start();
(new MyThread(2, 'C')).start();
}
}
运行结果:
ABCABCABCABCABCABCABCABCABCABC
本文展示了一个使用Java实现的线程同步示例,通过三个线程按顺序打印字符'A'、'B'、'C',每个字符打印10次,确保线程间的正确同步。该示例利用`synchronized`关键字和`wait()`、`notifyAll()`方法来控制线程执行顺序。

被折叠的 条评论
为什么被折叠?



