为什么代码中线程VolatileExample 不会终止
package thread;
public class VolatileExample extends Thread{
private static boolean flag = false;
@Override
public void run() {
while (!flag) {
//System.out.println(1);
}
}
public static void main(String[] args) throws InterruptedException {
VolatileExample v = new VolatileExample();
v.start();
Thread.sleep(1000);
flag = true;
}
}
而
package thread;
public class VolatileExample extends Thread{
private static boolean flag = false;
@Override
public void run() {
while (!flag) {
System.out.println(1);
}
}
public static void main(String[] args) throws InterruptedException {
VolatileExample v = new VolatileExample();
v.start();
Thread.sleep(1000);
flag = true;
}
}
却可以正常终止。
还有这样
package thread;
public class VolatileExample extends Thread{
private static volatile boolean flag = false;
@Override
public void run() {
while (!flag) {
//System.out.println(1);
}
}
public static void main(String[] args) throws InterruptedException {
VolatileExample v = new VolatileExample();
v.start();
Thread.sleep(1000);
flag = true;
}
}
线程也可以正常终止。。。求大神指导。。