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
但是子线程没有退出

浙公网安备 33010602011771号