public class MyThread extends Thread{
private boolean isRunning = true ;
public void run(){
System.out.println(this.currentThread().getName() + " start");
while(isRunning){
System.out.println(this.currentThread().getName() + " is running.");
}
System.out.println(this.currentThread().getName() + " stop");
}
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread.sleep(100);
Thread t1 = new Thread(myThread,"t1");
t1.start();
Thread.sleep(100); // 这三秒钟内,线程完成了从主内存复制数值。三秒之后,再次改变isRunning的值后,线程则不受影响。
// 但是,如果没有此行代码。则线程在启动的一瞬间,isRunning就被设置成了false,所以就在开启线程的一瞬间,就结束了。
// 如果想在不同线程间,访问统一变量,需要在改变量前加volatile修饰。
myThread.isRunning = false;
}
}
vilatile只能保证原子性操作的线程安全
在run方法中,syso打印和不打印,其运行流程不同。为什么?
System.out.println(this.currentThread().getName() + " is running.");
不注释 运行结果如下:
t1 start
t1 is running.
... ...
t1 is running.
t1 stop
注释,运行结果如下:
t1 start
现象上看,一个方法执行正常结束,一个方法持续执行。
时隔多年,再次温故而知新,发现println里面有加了synchronized,导致线程同步了内存,,,
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
http://www.importnew.com/20566.html
如果是myThread.isRunning = false;这样的赋值可以使用volatile