count小于100,打印出来却是0--100,
来源:7-7 交替打印

坂田渣渣辉
2019-10-28
感觉有问题,最后100是怎么打印出来的?
写回答
3回答
-
悟空
2019-10-28
99的时候,两个线程都进入while,然后一个打印99,然后把99变成了100,另外一个已经在while里面了,不会再判断条件了,所以会把100打印出来。
10 -
坂田渣渣辉
提问者
2019-10-28
package threadcoreknowledge.createthreads; public class PrintTest { private static int count ; private static final Object lock = new Object(); public static void main(String[] args){ // int count = 0; // Object lock = new Object(); System.out.println("start---"); new Thread(new Runnable() { @Override public void run() { synchronized (lock){ while (count<100){ if ((count & 1) == 0){ System.out.println(Thread.currentThread().getName()+":"+ count++); waitNotify(); } } } } }, "偶数").start(); new Thread(new Runnable() { @Override public void run() { synchronized (lock){ while (count<100){ if ((count & 1) == 1){ System.out.println(Thread.currentThread().getName()+":"+count++); waitNotify(); } } } } }, "基数").start(); } public static void waitNotify(){ lock.notifyAll(); if (count<100){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } 需要把count放到共享代码块中,
00 -
悟空
2019-10-28
条件是<100,所以99的时候可以进入while,然后count++,count变成100,然后打印出来。
052019-10-28
相似问题