适用场景
创建2个线程,线程名称分别为“奇”,“偶”;
要求2个线程交替执行,分别打印1~10的奇偶数;
关键字
java synchronized notify wait notifyAll
源代码
public class OddEven {
private static int i = 1;
private static Object o = new Object();
private static Thread t1 = new MyThread("奇 ");
private static Thread t2 = new MyThread("偶 ");
public static void main(String[] args) {
t1.start();
t2.start();
}
private static class MyThread extends Thread {
MyThread(String name) {
super(name);
}
public void run() {
try {
synchronized (o) {
while (i <= 10) {
System.out.println(getName() + (i++));
o.notify();
o.wait();
}
o.notifyAll();
}
System.out.println(getName() + " over");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
输出结果
如果去掉synchronized
,如下所示,则无法实现预期结果:
参考
https://jingyan.baidu.com/album/20095761feaa9fcb0721b4d2.html?picindex=4