1. 程式人生 > >JAVA模擬高併發及多執行緒計數器

JAVA模擬高併發及多執行緒計數器

1、多執行緒高併發模擬實現可採用閉鎖CountDownLatch,設定對應執行緒數的CountDownLatch,達到就緒條件後會多執行緒統一執行。這裡只是單機模擬,因為執行緒採用搶佔式執行方式,並不能完全模擬統一同時執行。

2、多執行緒計數器可採用悲觀鎖CAS實現類AtomicInteger等原子操作方法實現。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ***************************************************************************
 * Description  :
 * Author       : cxx
 * Creation date: 2018/10/11.
 * Version      : 1.0
 * ***************************************************************************
 */
public class HighConcurrencyTest {
    public static void main(String[] args) {
        //這裡的Runnable知識一個執行介面,後續放到Tread中作為統一執行實體,所以變數counter共享
        Runnable runnable = new Runnable() {
            private AtomicInteger counter = new AtomicInteger(0);

            @Override
            public void run() {
                //do something
                for (int i = 0; i < 100; i++) {
                    System.out.println(System.nanoTime() + " Thread:" + Thread.currentThread().getName() + "  Count:" + counter.incrementAndGet());
                }
            }
        };
        System.out.println("******** cost[ns]:" + startAllInOne(10, runnable));
    }

    public static long startAllInOne(int num, final Runnable runnable) {

        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(num);
        for (int i = 0; i < num; i++) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        startGate.await();  //等待開始門計數到0
                        try {
                            runnable.run();
                        } finally {
                            endGate.countDown(); //結束門計數減1,為最後所有執行緒結束後計時(或其它操作)做準備
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
        long startTime = System.nanoTime();
        System.out.println(System.nanoTime() + " All thread are reading starting");
        startGate.countDown();  //先通過第一道門 然後執行緒統一進入開始執行
        try {
            //開啟結束門,基本執行到此處countDownLatch已經為0,如果執行緒或執行緒執行耗時足夠多這裡才會有作用,所有執行結果會統一通過結束門
            endGate.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //結束門開啟後這裡的計時才會準確,因為所有執行緒都執行完畢
        return System.nanoTime() - startTime;
    }
}