对于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