老师这段代码 如果将if提取到synchronized外面有几率输出不到100 这是因为?
来源:7-7 交替打印

慕设计10038
2020-03-09
/**
-
两个线程交替打印100以内奇偶数 使用 syn方式实现 如果将if提取的synchronized外面有几率输出不到100 这是因为?
*/
public class WaitNotifyPrintOddEvenSyn {
private static int count = 0;
private static final Object lock = new Object();/**
-
1创建2个线程 2实现奇偶数输出
-
@param args
*/
public static void main(String[] args) {new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
if ((count & 1) == 0) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + “:” + count++);
}
}
}
}
}, “偶数”).start();new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
if ((count & 1) == 1) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + “:” + count++);
}
}
}
}
}, “奇数”).start();
}
-------------------如下图说所示,上述代码把if的流程控制包在synchronized代码块儿外几率输出不到100---------------------
-
1回答
-
悟空
2020-03-09
因为while里面就是小于100的条件,到99就停了
042020-06-10
相似问题