java多线程快速入门(十五)

使用violate关键字解决了变量的可见性问题(volatile让多线程刷新falg的值)

package com.cppdy;

class MyThread11 extends Thread {

    //volatile让多个线程刷新falg的值
    public volatile boolean falg = true;

    @Override
    public void run() {
        System.out.println("子线程开始执行啦");
        while (falg) {

        }
        System.out.println("子线程结束执行啦");
    }

    public void setFalg(boolean falg) {
        this.falg=falg;
        System.out.println("falg的值:"+this.falg);
    }
}

public class ThreadDemo11 {

    public static void main(String[] args) throws Exception {
        MyThread11 mt = new MyThread11();
        mt.start();
        Thread.sleep(1000);
        mt.setFalg(false);
        System.out.println("主线程结束啦");
    }

}

当更改falg的值,volatile会更新其它线程falg的值

posted @ 2018-11-25 16:24  知识追求者  阅读(153)  评论(0编辑  收藏  举报