volatile

http://www.cnblogs.com/hapjin/p/5492880.html 

volatile变量每次取值不从副本里面取,所以获得的值是最新的。

package one;

public class Batch {

    public static void main(String[] args) {
        TaskThread thread = new TaskThread();
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (thread != null) {
            thread.setStatus(false);
        }

        System.out.println("exit");
    }

}

 

package one;

public class TaskThread extends Thread {

    private volatile boolean running;
    // private boolean running;

    public TaskThread() {
        running = true;
    }

    public void setStatus(boolean running) {
        this.running = running;
    }

    @Override
    public void run() {
        System.out.println("run");
        while (running) {

        }

        new Thread() {

            @Override
            public void run() {
                System.out.println("subthread run");

                while (running) {

                }

                System.out.println("subthread end");
            }

        }.start();

        System.out.println("end");
    }
}

运行结果:

run
exit
end
subthread run
subthread end

 

如果替换成 private boolean running;

run
exit

但是子线程没有退出

 

posted @ 2017-01-20 10:57  牧 天  阅读(117)  评论(0)    收藏  举报