两条线程交替输出1-100的数字
public class Demo {
static Integer num = 1;
public static void main(String[] args) {
new Thread(() -> {
Thread.currentThread().setName("A");
while (true) {
synchronized (num) {
if (num > 100){
break;
}
if (num % 2 == 0) { // 偶数
System.out.println(Thread.currentThread().getName() + " " + num++);
}
}
}
}).start();
new Thread(() -> {
Thread.currentThread().setName("B");
while (true) {
synchronized (num) {
if (num > 100){
break;
}
if (num % 2 != 0) { //奇数
System.out.println(Thread.currentThread().getName() + " " + num++);
}
}
}
}).start();
}
}
再贴某一次的输出结果
A 86
B 87
A 88
B 89
B 91
A 90 *
A 92 *
A 94 *
B 93
在同步代码块中处理数字,为啥输出结果还是有问题