怎么执行都是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();
}
}
加注释,多次编译,多次执行。
基本上循环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(); } }