對於java來說有一個關鍵字不是很好理解,那就是volatile關鍵字。java
public class VolatileDemo { private static volatile int INIT_VALUE = 0; //使用後效果 // private static int INIT_VALUE = 0; //使用前效果 private static final int MAXINT = 5; public static void main(String[] args) { /** * 定義線程一 */ Thread tReader = new Thread(()->{ int localint = INIT_VALUE; while(localint < MAXINT){ if(localint != INIT_VALUE){ Optional.of(Thread.currentThread().getName() + " the value is " + localint).ifPresent(System.out::println); localint = INIT_VALUE; } //Optional.of(Thread.currentThread().getName()+" values is "+ localint +" and " + INIT_VALUE).ifPresent(System.out::println); } },"thread-reader"); tReader.start(); Thread tWriter = new Thread(()->{ int localint = 0; while(localint < MAXINT){ try { Thread.sleep(100L); } catch (InterruptedException e) { e.printStackTrace(); } Optional.of(Thread.currentThread().getName() + " update the value " + (++localint)).ifPresent(System.out::println); INIT_VALUE = localint; } },"thread-writer"); tWriter.start(); System.out.println("the main thread is finished..."); } }
使用前:線程
使用後:3d
總結:blog
1)保證了不一樣線程對這個變量進行操做時的可見性,即一個線程修改了某個變量的值,這新值對其餘線程來講是當即可見的。排序
2)禁止進行指令重排序。內存
一、在對變量進行修改的時候,修改本身線程的cup cache的時候,同事刷回主內存;get
二、可是在讀取的時候,則不會重新去主內存拿,除非使用volatile進行修飾;it