1.7volatile keyword

volatile

The main role of the volatile keyword is visible in the variables between multiple threads

Instructions:

private volatile int number=0;

Icon:

 

 

 Two threads share a data t1 and t2, int a = 0, but between the two threads are not visible, t1 modify a = 10, but for a t2 is from 0 to 20, or, two independent threads and invisible;

If I want to do it is a change, and real-time t1 and t2 know a change, and that is not a change from 0-20, but a change from 10 to 20; that is, the occurrence of changes to a t1, t2 know a real-time changes a; Similarly, t2 in a 20 into a, t1 can now know the value becomes 20; volatile keyword can achieve this.

 

 Results are as follows:

 

 Although isRunning output value has been set to false, but the thread is still running; this is what causes it?

This is why the java jdk

java jdk in the implementation of a program, will be allocated a separate space, but after jdk1.5, each thread to make it an optimized, plus a piece of thread for each run independent space, this space of main memory installed Some references (references to some of the current thread variable), the equivalent of a copy of a copy, go directly to get a copy of the contents of the thread is running. the aim is to make more efficient when executing thread

 

 After plus volatile keyword:

 

 Why is this?

Memory analysis chart:

 

 volatile only have visibility does not have the atomic (atomic operation is indivisible, is finished will not be interrupted at any other tasks or events)

 

Guess you like

Origin www.cnblogs.com/curedfisher/p/11981973.html