先看下不加volatile关键字的例子
public class ThreadVerify {
public static Boolean stop = false;
public static void main(String args[]) throws InterruptedException {
Thread testThread = new Thread(){
@Override
public void run(){
int i = 1;
while(!stop){
//System.out.println("in thread: " + Thread.currentThread() + " i: " + i);
i++;
}
System.out.println("Thread stop i="+ i);
}
}
;
testThread.start();
Thread.sleep(1000);
stop = true;
System.out.println("now, in main thread stop is: " + stop);
testThread.join();
}
}
运行结果
image.png
运行起来你会发现进入了死循环
纳闷了不是已经stop设成true了吗?为何还是循环呢?
因为工作线程开启之后把stop变量复制到工作内存当中也就是默认的false,主线程虽然1s之后设置true了但是设置的主内存的值,线程工作内存的值依然还是false导致一直死循环。
解决的方式就是stop变量前加一个volatile
因为加上volatile之后读写都是直接从主内存中的操作的,所以主线程设置true之后工作线程读的主内存的值也就是stop=true,自然也就跳出循环了。
public class ThreadVerify {
public volatile static Boolean stop = false;
public static void main(String args[]) throws InterruptedException {
Thread testThread = new Thread(){
@Override
public void run(){
int i = 1;
while(!stop){
//System.out.println("in thread: " + Thread.currentThread() + " i: " + i);
i++;
}
System.out.println("Thread stop i="+ i);
}
}
;
testThread.start();
Thread.sleep(1000);
stop = true;
System.out.println("now, in main thread stop is: " + stop);
testThread.join();
}
}
运行结果
image.png
网友评论