public class SynchronizedDemo2 {
private boolean ready = false;
private int result = 0;
private int number = 1;
public synchronized void write() {
ready = true;
number = 2;
}
public synchronized 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;
}
@Override
public void run() {
if (flag) {
write();
} else {
read();
}
}
}
public static void main(String[] args) {
for (int i = 0; i < 5000; i++) {
SynchronizedDemo2 demo = new SynchronizedDemo2();
demo.new ReadWriteThread(true).start();
demo.new ReadWriteThread(false).start();
}
}
}