java多线程学习之volatile

来源:互联网 发布:ido抑制剂 知乎 编辑:程序博客网 时间:2024/06/05 08:24
package learn.thread;/* * volatile关键字,被volatile修饰的变量 */public class Demo8 extends Thread {    public volatile static boolean open = true;    public volatile static int num = 0;    // public boolean open = true;//不用volatile也可能可以停止,volatile的特性比较难测出    public Demo8(String name) {        super(name);    }    String name;    @Override    public void run() {        while (open) {            System.out.println("循环");        }        System.out.println("while循环停止");        System.out.println("num: " + num);    }    public static void main(String[] args) {        Demo8 t1 = new Demo8("A");        t1.start();        try {            Thread.sleep(10);        } catch (InterruptedException e) {            e.printStackTrace();        }        Demo8.open = false;        Demo8.num = 5;    }}// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// 循环// while循环停止// num: 5
原创粉丝点击