为啥我的代码没有Volatile和Synchronized修饰保证可见性,还是会有可见性呢?
public class SynchronizedClass {
private int value = 100;
public static void main(String[] args) throws InterruptedException {
SynchronizedClass s = new SynchronizedClass();
SynchronizedThread synchronizedThread = new SynchronizedThread(s);
Thread t = new Thread(synchronizedThread);
SynchronizedThread2 synchronizedThread2 = new SynchronizedThread2(s);
Thread t2 = new Thread(synchronizedThread2);
t2.start();
t.start();
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
class SynchronizedThread implements Runnable {
private SynchronizedClass obj;
public SynchronizedThread(SynchronizedClass obj) {
this.obj = obj;
}
@Override
public void run() {
while (obj.getValue() == 100) {
}
System.out.println("end");
}
}
class SynchronizedThread2 implements Runnable {
private SynchronizedClass obj;
public SynchronizedThread2(SynchronizedClass obj) {
this.obj = obj;
}
@Override
public void run() {
obj.setValue(0);
int i = 0;
while (true) {
i++;
}
}
}