熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

java的volatile與多線程

2013-11-23 19:40:55  來源: Java高級技術 

  Java語言規范中指出為了獲得最佳速度允許線程保存共享成員變量的私有拷貝而且只當線程進入或者離開同步代碼塊時才與共享成員變量的原始值對比

  Volatile修飾的成員變量在每次被線程訪問時都強迫從共享內存中重讀該成員變量的值而且當成員變量發生變化時強迫線程將變化值回寫到共享內存這樣在任何時刻兩個不同的線程總是看到某個成員變量的同一個值

  下面是個例子恢復注釋的任何一處都可以實現同步就是讓程序停下來

  Java代碼

  import ncurrentTimeUnit;

  // Broken! How long would you expect this program to run ?

  public class StopThread {

  //  private static volatile   boolean stopRequested;  // value: false

  private static   boolean stopRequested;  // value: false

  public static void main(String args) throws InterruptedException {

  Thread backgroundThread = new Thread(new Runnable() {

  public synchronized  void test () {

  }

  @Override

  public void run() {

  int i = ;

  while(!stopRequested){

  //                  test();

  i++;

  }

  }

  });

  backgroundThreadstart();

  TimeUnitSECONDSsleep();

  stopRequested = true;

  }

  }

  當然最容易理解的是用同步的方法

  Java代碼

  import ncurrentTimeUnit;

  // Broken! How long would you expect this program to run ?

  public class StopThread {

  private static boolean stopRequested;  // value: false

  public static synchronized void requestStop() {

  stopRequested = true;

  }

  public static synchronized boolean stopRequested() {

  return stopRequested;

  }

  public static void main(String args) throws InterruptedException {

  Thread backgroundThread = new Thread(new Runnable() {

  @Override

  public void run() {

  int i = ;

  while(!stopRequested())

  i++;

  }

  });

  backgroundThreadstart();

  TimeUnitSECONDSsleep();

  requestStop();

  }

  }


From:http://tw.wingwit.com/Article/program/Java/gj/201311/27280.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.