Java Volatile的一个实际应用场合_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java Volatile的一个实际应用场合

Java Volatile的一个实际应用场合

 2021/3/17 12:50:33  JerryWang_SAP  程序员俱乐部  我要评论(0)
  • 摘要:Considerthefollowingexample:packagethread;publicclassThreadVerify{publicstaticbooleanstop=false;publicstaticvoidmain(Stringargs[])throwsInterruptedException{ThreadtestThread=newThread(){@Overridepublicvoidrun(){inti=1;while(!stop){//System.out
  • 标签:Java 一个 应用 实际应用

Consider the following example:

class="language-java" style="margin: 0px; padding: 0px; border-radius: 0px; font-family: Menlo, Monaco, Consolas, 'Andale Mono', 'lucida console', 'Courier New', monospace; font-size: inherit; background-color: inherit;">package thread;
public class ThreadVerify {
  public static boolean  stop = false;
  public static void main(String args[]) throws InterruptedException {
      Thread testThread = new Thread(){
            @Override
            public void run(){
              int i = 1;
              while(!stop){
               //System.out.println("in thread: " + Thread.currentThread() + " i: " + i);
                  i++;
              }
              System.out.println("Thread stop i="+ i);
           }
         };
         testThread.start();
         Thread.sleep(1000);
         stop = true;
         System.out.println("now, in main thread stop is: " + stop);
         testThread.join();
     }
 }

The working thread is started to do increment on i and after one second, the flag is set as true in main thread. It is expected that we could see print out in working thread: “Thread stop i=”. Unfortunately it is NOT the case. Through process explorer we can find the working thread is still running:

?

?

The only way we can terminate it is to click this button in Eclipse:

?

?

The reason is: every thread in Java has its own thread local stack in runtime. Every time a thread tries to access the content of a variable, it first locates the variable content in the main memory, then loads this content from main memory to its local stack. Once this load is done, this relationship between thread local stack and main memory is cut.

Later, when thread performs modifications on the variable, the change is directly done on thread local stack. And at a given time ( scheduled by JVM, developer has no control about this timeslot), the change will be refreshed from thread local stack to memory. Back to our example, already the main thread has changed the flag to true in one second later ( this is TOO late! ), unfortunately when the working thread reads the flag from its own local stack, the flag is still false ( it makes sense since when it is copied from main memory in main thread ), so the working threads could never end. See the following picture for detail.

?

?

Solution is: add keyword volatile to flag variable, to force the read access on it in working thread is done always from main memory, so that after the flag is changed to true in main thread, later the working thread can detect this latest change since it reads data from main memory now. After this keyword is added we can get expected output:

?

?

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

发表评论
用户名: 匿名