/**
两个线程交替打印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---------------------