标签:线程 col except round getname 设置 string read 分享图片
1. 改成static也不行 private static boolean isRunning = true; volatile关键字主要用于线程变量在多个线程之间的可见
1 public class RunThread extends Thread{ 2 private volatile boolean isRunning = true; 3 public void setRunning(boolean isRunning) { 4 System.out.println(Thread.currentThread().getName()+"线程setRunning"); 5 this.isRunning = isRunning; 6 } 7 8 public void run(){ 9 System.out.println(Thread.currentThread().getName()+"进入run方法..."); 10 while(isRunning) { 11 //System.out.println(Thread.currentThread().getName()+"线程isRunning"); 12 } 13 System.out.println(Thread.currentThread().getName()+"线程终止"); 14 } 15 16 public static void main(String[] args) throws Exception { 17 RunThread rt = new RunThread(); 18 rt.start(); 19 Thread.sleep(3000); 20 rt.setRunning(false); 21 System.out.println(Thread.currentThread().getName()+"线程isRunning值被设置成false"); 22 Thread.sleep(100); 23 System.out.println(Thread.currentThread().getName()+"::"+rt.isRunning); 24 } 25 /* 不加volatile关键字, 主内存中的isRunning不会被刷新,永远都是true.所以线程不会终止,加了会把rt线程的工作内存变量刷新到主内存 26 * Thread-0进入run方法... 27 main线程setRunning 28 main线程isRunning值被设置成false 29 main::false 30 */ 31 }
多线程7---volatile关键字,刷新线程工作空间内存到主内存中去,即保持同步
标签:线程 col except round getname 设置 string read 分享图片
原文地址:http://www.cnblogs.com/bravolove/p/7944500.html