package thread.key; public class TestOne { private volatile boolean bChange; public static void main(String[] args) { /** * * --------- volatile * volatile是一種輕量級的同步,相對 synchronized開銷小 * 所謂可見性,是指當一條線程修改了共享變量的值,新值對於其餘線程來講是能夠當即得知的。 * * * 1)寫一個volatile變量時,JMM會將本地內存的變量強制刷新到主內存中去 * 2)會使其餘內存中的值無效 * * * * * final * * * 原子性 * * */ try { TestOne testOne = new TestOne(); new Thread(){ public void run() { for(;;){ // System.out.println(Thread.currentThread()); testOne.changeStatus(); testOne.print(Thread.currentThread().toString()); } }; }.start(); Thread.sleep(1); new Thread(){ public void run() { for(;;){ // System.out.println(Thread.currentThread()); // TestOne testOne = new TestOne(); // testOne.changeStatus(); testOne.print(Thread.currentThread().toString()); } }; }.start(); } catch (Exception e) { e.printStackTrace(); } } public void changeStatus(){ bChange = true; } public void print(String str){ if (bChange) { System.out.println("-----"+str); }else { System.out.println(str); } } }