国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

各種同步方法性能比較(synchronized,ReentrantLock,Atomic)

2019-11-14 12:02:08
字體:
供稿:網(wǎng)友

轉(zhuǎn)自:http://zzhonghe.VEvb.com/blog/826162

5.0的多線程任務(wù)包對于同步的性能方面有了很大的改進,在原有synchronized關(guān)鍵字的基礎(chǔ)上,又增加了ReentrantLock,以及各種Atomic類。了解其性能的優(yōu)劣程度,有助與我們在特定的情形下做出正確的選擇。 

總體的結(jié)論先擺出來:  

synchronized: 

在資源競爭不是很激烈的情況下,偶爾會有同步的情形下,synchronized是很合適的。原因在于,編譯程序通常會盡可能的進行優(yōu)化synchronize,另外可讀性非常好,不管用沒用過5.0多線程包的程序員都能理解。 

ReentrantLock: 

ReentrantLock提供了多樣化的同步,比如有時間限制的同步,可以被Interrupt的同步(synchronized的同步是不能Interrupt的)等。在資源競爭不激烈的情形下,性能稍微比synchronized差點點。但是當(dāng)同步非常激烈的時候,synchronized的性能一下子能下降好幾十倍。而ReentrantLock確還能維持常態(tài)。 

Atomic: 

和上面的類似,不激烈情況下,性能比synchronized略遜,而激烈的時候,也能維持常態(tài)。激烈的時候,Atomic的性能會優(yōu)于ReentrantLock一倍左右。但是其有一個缺點,就是只能同步一個值,一段代碼中只能出現(xiàn)一個Atomic的變量,多于一個同步無效。因為他不能在多個Atomic之間同步。 所以,我們寫同步的時候,優(yōu)先考慮synchronized,如果有特殊需要,再進一步優(yōu)化。ReentrantLock和Atomic如果用的不好,不僅不能提高性能,還可能帶來災(zāi)難。 先貼測試結(jié)果:再貼代碼(Atomic測試代碼不準(zhǔn)確,一個同步中只能有1個Actomic,這里用了2個,但是這里的測試只看速度) ========================== round:100000 thread:5 Sync = 35301694 Lock = 56255753 Atom = 43467535 ========================== round:200000 thread:10 Sync = 110514604 Lock = 204235455 Atom = 170535361 ========================== round:300000 thread:15 Sync = 253123791 Lock = 448577123 Atom = 362797227 ========================== round:400000 thread:20 Sync = 16562148262 Lock = 846454786 Atom = 667947183 ========================== round:500000 thread:25 Sync = 26932301731 Lock = 1273354016 Atom = 982564544 java代碼  收藏代碼package test.thread;    import static java.lang.System.out;    import java.util.Random;  import java.util.concurrent.BrokenBarrierException;  import java.util.concurrent.CyclicBarrier;  import java.util.concurrent.ExecutorService;  import java.util.concurrent.Executors;  import java.util.concurrent.atomic.AtomicInteger;  import java.util.concurrent.atomic.AtomicLong;  import java.util.concurrent.locks.ReentrantLock;    public class TestSyncMethods {            public static void test(int round,int threadNum,CyclicBarrier cyclicBarrier){          new SyncTest("Sync",round,threadNum,cyclicBarrier).testTime();          new LockTest("Lock",round,threadNum,cyclicBarrier).testTime();          new AtomicTest("Atom",round,threadNum,cyclicBarrier).testTime();      }        public static void main(String args[]){                    for(int i=0;i<5;i++){              int round=100000*(i+1);              int threadNum=5*(i+1);              CyclicBarrier cb=new CyclicBarrier(threadNum*2+1);              out.PRintln("==========================");              out.println("round:"+round+" thread:"+threadNum);              test(round,threadNum,cb);                        }      }  }    class SyncTest extends TestTemplate{      public SyncTest(String _id,int _round,int _threadNum,CyclicBarrier _cb){          super( _id, _round, _threadNum, _cb);      }      @Override      /**      * synchronized關(guān)鍵字不在方法簽名里面,所以不涉及重載問題      */      synchronized long  getValue() {          return super.countValue;      }      @Override      synchronized void  sumValue() {          super.countValue+=preInit[index++%round];      }  }      class LockTest extends TestTemplate{      ReentrantLock lock=new ReentrantLock();      public LockTest(String _id,int _round,int _threadNum,CyclicBarrier _cb){          super( _id, _round, _threadNum, _cb);      }      /**      * synchronized關(guān)鍵字不在方法簽名里面,所以不涉及重載問題      */      @Override      long getValue() {          try{              lock.lock();              return super.countValue;          }finally{              lock.unlock();          }      }      @Override      void sumValue() {          try{              lock.lock();              super.countValue+=preInit[index++%round];          }finally{              lock.unlock();          }      }  }      class AtomicTest extends TestTemplate{      public AtomicTest(String _id,int _round,int _threadNum,CyclicBarrier _cb){          super( _id, _round, _threadNum, _cb);      }      @Override      /**      * synchronized關(guān)鍵字不在方法簽名里面,所以不涉及重載問題      */      long  getValue() {          return super.countValueAtmoic.get();      }      @Override      void  sumValue() {          super.countValueAtmoic.addAndGet(super.preInit[indexAtomic.get()%round]);      }  }  abstract class TestTemplate{      private String id;      protected int round;      private int threadNum;      protected long countValue;      protected AtomicLong countValueAtmoic=new AtomicLong(0);      protected int[] preInit;      protected int index;      protected AtomicInteger indexAtomic=new AtomicInteger(0);      Random r=new Random(47);      //任務(wù)柵欄,同批任務(wù),先到達wait的任務(wù)掛起,一直等到全部任務(wù)到達制定的wait地點后,才能全部喚醒,繼續(xù)執(zhí)行      private CyclicBarrier cb;      public TestTemplate(String _id,int _round,int _threadNum,CyclicBarrier _cb){          this.id=_id;          this.round=_round;          this.threadNum=_threadNum;          cb=_cb;          preInit=new int[round];          for(int i=0;i<preInit.length;i++){              preInit[i]=r.nextInt(100);          }      }            abstract void sumValue();      /*      * 對long的操作是非原子的,原子操作只針對32位      * long是64位,底層操作的時候分2個32位讀寫,因此不是線程安全      */      abstract long getValue();        public void testTime(){          ExecutorService se=Executors.newCachedThreadPool();          long start=System.nanoTime();          //同時開啟2*ThreadNum個數(shù)的讀寫線程          for(int i=0;i<threadNum;i++){              se.execute(new Runnable(){                  public void run() {                      for(int i=0;i<round;i++){                          sumValue();                      }                        //每個線程執(zhí)行完同步方法后就等待                      try {                          cb.await();                      } catch (InterruptedException e) {                          // TODO Auto-generated catch block                          e.printStackTrace();                      } catch (BrokenBarrierException e) {                          // TODO Auto-generated catch block                          e.printStackTrace();                      }                      }              });              se.execute(new Runnable(){                  public void run() {                        getValue();                      try {                          //每個線程執(zhí)行完同步方法后就等待                          cb.await();                      } catch (InterruptedException e) {                          // TODO Auto-generated catch block                          e.printStackTrace();                      } catch (BrokenBarrierException e) {                          // TODO Auto-generated catch block                          e.printStackTrace();                      }                    }              });          }                    try {              //當(dāng)前統(tǒng)計線程也wait,所以CyclicBarrier的初始值是threadNum*2+1              cb.await();          } catch (InterruptedException e) {              // TODO Auto-generated catch block              e.printStackTrace();          } catch (BrokenBarrierException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }          //所有線程執(zhí)行完成之后,才會跑到這一步          long duration=System.nanoTime()-start;          out.println(id+" = "+duration);                }    }  
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 平罗县| 贡山| 双柏县| 抚远县| 梅州市| 兴山县| 丽江市| 那曲县| 永安市| 平原县| 玉龙| 隆德县| 大渡口区| 靖边县| 龙州县| 宁海县| 交口县| 卓资县| 靖西县| 通州区| 莱州市| 花莲市| 漯河市| 武功县| 吉木萨尔县| 齐河县| 京山县| 宜州市| 成都市| 临邑县| 调兵山市| 丽水市| 肥东县| 五常市| 鸡泽县| 静宁县| 公主岭市| 梁平县| 惠来县| 仪陇县| 城步|