问答详情
源自:3-4 synchronized实现可见性代码(下)

没出现0的结果

怎么执行都是6,是版本太新了,还是电脑太慢了~唉~

public class SynchronizedDemo {

private boolean ready = false;

private int result=0;

private int number=1;

public void write(){

ready = true;

number =2;

}

public void read(){

if(ready){

result = number*3;

}

System.out.println("result的值是"+result);

}

private class ReadWriteThread extends Thread{

private boolean flag;

public ReadWriteThread(boolean flag){

this.flag = flag;

}

public void run(){

if(flag){

write();

}else{

read();

}

}

}

public static void main(String[] args){

SynchronizedDemo synDemo = new SynchronizedDemo();

synDemo.new ReadWriteThread(true).start();

synDemo.new ReadWriteThread(false).start();

}

}


提问者:starkpan 2017-06-26 23:11

个回答

  • Peng_0008
    2017-06-27 19:20:39
    已采纳

    加注释,多次编译,多次执行。

  • MichaelDuan
    2020-10-08 08:29:09

    基本上循环100000次没有出现过0,

    这样循环没有出现0的场景:
    public static void main(String[] args) {
        SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
        for (int i = 0; i < 100000; i++) {
            synchronizedDemo.new SynchronizedDemoThread(true).start();
            synchronizedDemo.new SynchronizedDemoThread(false).start();
        }
    }
    
    这样循环可以出现1的场景:
    public static void main(String[] args) {
        for (int i = 0; i < 100000; i++) {
            SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
            synchronizedDemo.new SynchronizedDemoThread(true).start();
            synchronizedDemo.new SynchronizedDemoThread(false).start();
        }
    }