Please take a look at the code below. I know why I don't use the "synchronized" part, the loop will never break, but what I don't know is why I use the "synchronized" part, the loop breaks. It seems don't match the Happens-Before principle.please help me out, thank you very much.
public class Test implements Runnable {
private String s = "continue";
@Override
public void run() {
while (!"break".equals(this.s)) {
//synchronized (this){
//
//}
}
System.out.println("loop has been breaked!");
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
Thread t1 = new Thread(test);
t1.start();
TimeUnit.SECONDS.sleep(1);
test.s = "break";
}
}