<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          如果保證多線程場景下的線程安全?

          共 7479字,需瀏覽 15分鐘

           ·

          2021-09-17 16:04

          點擊“藍字”,關(guān)注,置頂公眾號

          每日技術(shù)干貨,第一時間送達!


          1、引言

          當前隨著計算機硬件的快速發(fā)展,個人電腦上的 CPU 也是多核的,現(xiàn)在普遍的 CUP 核數(shù)都是 4 核或者 8 核的。因此,在編寫程序時,需要為了提高效率,充分發(fā)揮硬件的能力,則需要編寫并行的程序。Java 語言作為互聯(lián)網(wǎng)應(yīng)用的主要語言,廣泛應(yīng)用于企業(yè)應(yīng)用程序的開發(fā)中,它也是支持多線程Multithreading)的,但多線程雖好,卻對程序的編寫有較高的要求。

          單線程可以正確運行的程序不代表在多線程場景下能夠正確運行,這里的正確性往往不容易被發(fā)現(xiàn),它會在并發(fā)數(shù)達到一定量的時候才可能出現(xiàn)。這也是在測試環(huán)節(jié)不容易重現(xiàn)的原因。因此,多線程(并發(fā))場景下,如何編寫線程安全(Thread-Safety)的程序,對于程序的正確和穩(wěn)定運行有重要的意義。下面將結(jié)合示例,談?wù)勅绾卧?Java 語言中,實現(xiàn)線程安全的程序。

          為了給出感性的認識,下面給出一個線程不安全的示例,具體如下:

          package com.example.learn;
          public class Counter {
              private static int counter = 0;
              public static int getCount(){
                  return counter;
              }
              public static  void add(){
                  counter = counter + 1;
              }
          }1.2.3.4.5.6.7.8.9.10.

          這個類有一個靜態(tài)的屬性 counter,用于計數(shù)。其中可以通過靜態(tài)方法 add()對 counter 進行加 1 操作,也可以通過 getCount()方法獲取到當前的計數(shù) counter 值。如果是單線程情況下,這個程序是沒有問題的,比如循環(huán) 10 次,那么最后獲取的計數(shù) counter 值為 10。但多線程情況下,那么這個結(jié)果就不一定能夠正確獲取,可能等于 10,也可能小于 10,比如 9。下面給出一個多線程測試的示例:

          package com.example.learn;
          public class MyThread extends Thread{
              private String name ;
              public MyThread(String name){
                  this.name = name ;
              }
              public void run(){
                  Counter.add();
                  System.out.println("Thead["+this.name+"] Count is "+  Counter.getCount());
              }
          }
          ///////////////////////////////////////////////////////////
          package com.example.learn;
          public class Test01 {
              public static void main(String[] args) {
                  for(int i=0;i<5000;i++){
                      MyThread mt1 = new MyThread("TCount"+i);
                      mt1.start();
                  }
              }
          }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.

          這里為了重現(xiàn)計數(shù)的問題,線程數(shù)調(diào)至比較大,這里是 5000。運行此示例,則輸出可能結(jié)果如下:

          Thead[TCount5] Count is 4
          Thead[TCount2] Count is 9
          Thead[TCount4] Count is 4
          Thead[TCount14] Count is 10
          ..................................
          Thead[TCount4911] Count is 4997
          Thead[TCount4835] Count is 4998
          Thead[TCount4962] Count is 49991.2.3.4.5.6.7.8.

          注意:多線程場景下,線程不安全的程序輸出結(jié)果具有不確定性。

          2、synchronized 方法

          基于上述的示例,讓其變成線程安全的程序,最直接的就是在對應(yīng)的方法上添加 synchronized 關(guān)鍵字,讓其成為同步的方法。它可以修飾一個類,一個方法和一個代碼塊。對上述計數(shù)程序進行修改,代碼如下:

          package com.example.learn;
          public class Counter {
              private static int counter = 0;
              public static int getCount(){
                  return counter;
              }
              public static synchronized void add(){
                  counter = counter + 1;
              }
          }1.2.3.4.5.6.7.8.9.10.

          再次運行程序,則輸出結(jié)果如下:

          ......
          Thead[TCount1953] Count is 4998
          Thead[TCount3087] Count is 4999
          Thead[TCount2425] Count is 50001.2.3.4.

          3、加鎖機制

          另外一種常見的同步方法就是加鎖,比如 Java 中有一種重入鎖 ReentrantLock,它是一種遞歸無阻塞的同步機制,相對于 synchronized 來說,它可以提供更加強大和靈活的鎖機制,同時可以減少死鎖發(fā)生的概率。示例代碼如下:

          package com.example.learn;
          import java.util.concurrent.locks.ReentrantLock;
          public class Counter {
              private  static int counter = 0;
              private static final ReentrantLock lock = new ReentrantLock(true);
              public static int getCount(){
                  return counter;
              }
              public static  void add(){
                  lock.lock();
                  try {
                      counter = counter + 1;
                  } finally {
                      lock.unlock();
                  }
              }
          }1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.

          再次運行程序,則輸出結(jié)果如下:

          ......
          Thead[TCount1953] Count is 4998
          Thead[TCount3087] Count is 4999
          Thead[TCount2425] Count is 50001.2.3.4.

          注意:Java 中還提供了讀寫鎖 ReentrantReadWriteLock,這樣可以進行讀寫分離,效率更高。

          4、使用 Atomic 對象

          由于鎖機制會影響一定的性能,而有些場景下,可以通過無鎖方式進行實現(xiàn)。Java 內(nèi)置了 Atomic 相關(guān)原子操作類,比如 AtomicInteger,AtomicLong, AtomicBoolean 和 AtomicReference,可以根據(jù)不同的場景進行選擇。下面給出示例代碼:

          package com.example.learn;
          import java.util.concurrent.atomic.AtomicInteger;
          public class Counter {
              private static final AtomicInteger counter = new AtomicInteger();
              public static int getCount(){
                  return counter.get();
              }
              public static void add(){
                  counter.incrementAndGet();
              }
          }1.2.3.4.5.6.7.8.9.10.11.

          再次運行程序,則輸出結(jié)果如下:

          ......
          Thead[TCount1953] Count is 4998
          Thead[TCount3087] Count is 4999
          Thead[TCount2425] Count is 50001.2.3.4.

          5、無狀態(tài)對象

          前面提到,線程不安全的一個原因就是多個線程同時訪問某個對象中的數(shù)據(jù),數(shù)據(jù)存在共享的情況,因此,如果將數(shù)據(jù)變成獨享的,即無狀態(tài)(stateless)的話,那么自然就是線程安全的。而所謂的無狀態(tài)的方法,就是給同樣的輸入,就能返回一致的結(jié)果。下面給出示例代碼:

          package com.example.learn;
          public class Counter {
              public static int sum (int n) {
                  int ret = 0;
                  for (int i = 1; i <= n; i++) {
                      ret += i;
                  }
                  return ret;
              }
          }1.2.3.4.5.6.7.8.9.10.

          6、不可變對象

          前面提到,如果需要在多線程中共享一個數(shù)據(jù),而這個數(shù)據(jù)給定值,就不能改變,那么也是線程安全的,相當于只讀的屬性。在 Java 中可以通過 final 關(guān)鍵字進行屬性修飾。下面給出示例代碼:

          package com.example.learn;
          public class Counter {
              public final int count ;
              public Counter (int n) {
                  count = n;
              }
          }1.2.3.4.5.6.7.

          7、總結(jié)

          前面提到了幾種線程安全的方法,總體的思想要不就是通過鎖機制實現(xiàn)同步,要不就是防止數(shù)據(jù)共享,防止在多個線程中對數(shù)據(jù)進行讀寫操作。另外,有些文章中說到,可以在變量前使用 volatile 修飾,來實現(xiàn)同步機制,但這個經(jīng)過測試是不一定的,有些場景下,volatile 依舊不能保證線程安全。雖然上述是線程安全的經(jīng)驗總結(jié),但是還是需要通過嚴格的測試進行驗證,實踐是檢驗真理的唯一標準。


          瀏覽 21
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  久久亚洲天堂 | 成人做爰A片一区二区 | 日逼99 | 天天爽夜夜爽电影网 | 亚洲大骚逼 |