Thread之volatile关键字


volatile作用

使变量在多个线程间可见

通俗来说就是,当线程A对一个被volatile关键字修饰的变量进行修改,该变量对于其它线程是可见的,即线程每次获取该变量的值都是最新的。


场景一(普通类方法调用)

/**
 * 测试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方法执行结束----");
    }
}

运行结果

在这里插入图片描述

结论

main线程被卡在service.doSomething()方法中,无暇继续往下运行。


场景二(通过线程调用)

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方法执行结束----");
    }
}

运行结果

在这里插入图片描述

结论

  • 此时虽然可以正常停止,但是其原因是因为该线程还没有进入while循环的时候,isContinue的值就已经被改为false(在while循环加上简单的打印语句就可以测试出)
  • 如果将注释 Thread.sleep(100); 放开,又会进入死循环
  • 在这里插入图片描述

场景三(通过线程调用,用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方法执行结束----");
    }
}

运行结果

在这里插入图片描述

总结

在这里插入图片描述

推荐博客:
https://blog.csdn.net/tianjindong0804/article/details/105134458

猜你喜欢

转载自blog.csdn.net/single_0910/article/details/113705851