第一章、高併發引發的問題

示例模擬10000次請求,每次併發數爲100,每次請求,計數器加1,最後輸出計數器值。
上代碼:

package concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther:zhl
 * @Date:2019/7/13
 * @Description: 併發測試
 */
public class ConcurrentSample {
    //併發線程數量
    private static int users = 100;
    //訪問次數
    private static int count = 10000;
    //訪問總量
    private static int number = 0;

    public static void main(String[] args) {
        //定義線程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //併發量
        Semaphore semaphore = new Semaphore(users);
        for (int i = 0; i < count; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        System.out.println(number);
    }
    public static void add() {
        number++;
    }
}

計數器:9997
計數器:10000
計數器:9997
每次輸出結果不一致,這都是併發導致的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章