Thread's volatile keyword
Volatile role
Make variables visible between multiple threads .
In layman's terms, when thread A modifies a variable modified by the volatile keyword, the variable is visible to other threads, that is, the value of the variable is updated every time the thread obtains the variable .
Scenario one (calling ordinary class method)
/**
* 测试volatile关键字
* @author layman
*/
public class Demo09 {
public static void main(String[] args) throws InterruptedException {
Demo09Service service = new Demo09Service();
//死循环
service.doSomething();
System.out.println(Thread.currentThread().getName()+" 线程准备停止doSomething方法");
service.isContinue = false;
}
}
class Demo09Service extends Thread{
public boolean isContinue = true;
@Override
public void run() {
doSomething();
}
public void doSomething(){
System.out.println("doSomething方法执行开始----");
while(isContinue){
}
System.out.println("doSomething方法执行结束----");
}
}
operation result
in conclusion
The main thread is stuck in the service.doSomething() method and has no time to continue running.
Scenario Two (Called by thread)
public class Demo09 {
public static void main(String[] args) throws InterruptedException {
Demo09Service service = new Demo09Service();
//会正常停止,但是如果加上Thread.sleep(100); 就会进入死循环
service.start();
//Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" 线程准备停止doSomething方法");
service.isContinue = false;
}
}
class Demo09Service extends Thread{
public boolean isContinue = true;
@Override
public void run() {
doSomething();
}
public void doSomething(){
System.out.println("doSomething方法执行开始----");
while(isContinue){
}
System.out.println("doSomething方法执行结束----");
}
}
operation result
in conclusion
- Although it can stop normally at this time, the reason is because the value of isContinue has been changed to false when the thread has not entered the while loop (you can test it out by adding a simple print statement in the while loop)
- If you let go of the comment Thread.sleep(100);, it will enter an endless loop again
Scenario Three (Called by thread, modified with volatile)
package com.hanyxx.thread;
/**
* 测试volatile关键字
* @author layman
* @date 2021/2/6
*/
public class Demo09 {
public static void main(String[] args) throws InterruptedException {
Demo09Service service = new Demo09Service();
service.start();
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" 线程准备停止doSomething方法");
service.isContinue = false;
}
}
class Demo09Service extends Thread{
public volatile boolean isContinue = true;
@Override
public void run() {
doSomething();
}
public void doSomething(){
System.out.println("doSomething方法执行开始----");
while(isContinue){
}
System.out.println("doSomething方法执行结束----");
}
}
operation result
to sum up
Recommended blog:
https://blog.csdn.net/tianjindong0804/article/details/105134458