Java里使用volatile进行线程同步的一个例子

704 篇文章 8 订阅

Consider the following example:

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

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的原创文章,请关注公众号"汪子熙":

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汪子熙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值