Java中如何模擬真正的同時併發請求?

正文

有時須要測試一下某個功能的併發性能,又不要想借助於其餘工具,索性就本身的開發語言,來一個併發請求就最方便了。java

java中模擬併發請求,天然是很方便的,只要多開幾個線程,發起請求就行了。可是,這種請求,通常會存在啓動的前後順序了,算不得真正的同時併發!怎麼樣才能作到真正的同時併發呢?是本文想說的點,java中提供了閉鎖 CountDownLatch, 恰好就用來作這種事就最合適了。android

只須要:面試

  1. 開啓n個線程,加一個閉鎖,開啓全部線程;
  2. 待全部線程都準備好後,按下開啓按鈕,就能夠真正的發起併發請求了。
package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;

public class LatchTest {

    public static void main(String[] args) throws InterruptedException {
        Runnable taskTemp = new Runnable() {

       // 注意,此處是非線程安全的,留坑
            private int iCounter;

            @Override
            public void run() {
                for(int i = 0; i < 10; i++) {
                    // 發起請求
//                    HttpClientOp.doGet("https://www.baidu.com/");
                    iCounter++;
                    System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        LatchTest latchTest = new LatchTest();
        latchTest.startTaskAllInOnce(5, taskTemp);
    }

    public long startTaskAllInOnce(int threadNums, final Runnable task) throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(threadNums);
        for(int i = 0; i < threadNums; i++) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        // 使線程在此等待,當開始門打開時,一塊兒涌入門中
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            // 將結束門減1,減到0時,就能夠開啓結束門了
                            endGate.countDown();
                        }
                    } catch (InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            };
            t.start();
        }
        long startTime = System.nanoTime();
        System.out.println(startTime + " [" + Thread.currentThread() + "] All thread is ready, concurrent going...");
        // 因開啓門只需一個開關,因此立馬就開啓開始門
        startGate.countDown();
        // 等等結束門開啓
        endGate.await();
        long endTime = System.nanoTime();
        System.out.println(endTime + " [" + Thread.currentThread() + "] All thread is completed.");
        return endTime - startTime;
    }
}

其執行效果以下圖所示:數組

httpClientOp 工具類,可使用 成熟的工具包,也能夠本身寫一個簡要的訪問方法,參考以下:安全

class HttpClientOp {
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回結果字符串
        try {
            // 建立遠程url鏈接對象
            URL url = new URL(httpurl);
            // 經過遠程url鏈接對象打開一個鏈接,強轉成httpURLConnection類
            connection = (HttpURLConnection) url.openConnection();
            // 設置鏈接方式:get
            connection.setRequestMethod("GET");
            // 設置鏈接主機服務器的超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設置讀取遠程返回的數據時間:60000毫秒
            connection.setReadTimeout(60000);
            // 發送請求
            connection.connect();
            // 經過connection鏈接,獲取輸入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封裝輸入流is,並指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放數據
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 關閉遠程鏈接
        }

        return result;
    }

    public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 經過遠程url鏈接對象打開鏈接
            connection = (HttpURLConnection) url.openConnection();
            // 設置鏈接請求方式
            connection.setRequestMethod("POST");
            // 設置鏈接主機服務器超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設置讀取主機服務器返回數據超時時間:60000毫秒
            connection.setReadTimeout(60000);

            // 默認值爲:false,當向遠程服務器傳送數據/寫數據時,須要設置爲true
            connection.setDoOutput(true);
            // 默認值爲:true,當前向遠程服務讀取數據時,設置爲true,該參數無關緊要
            connection.setDoInput(true);
            // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 設置鑑權信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 經過鏈接對象獲取一個輸出流
            os = connection.getOutputStream();
            // 經過輸出流對象將參數寫出去/傳輸出去,它是經過字節數組寫出的
            os.write(param.getBytes());
            // 經過鏈接對象獲取一個輸入流,向遠程讀取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 對輸入流對象進行包裝:charset根據工做項目組的要求來設置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循環遍歷一行一行讀取數據
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 斷開與遠程地址url的鏈接
            connection.disconnect();
        }
        return result;
    }
}

如上,就能夠發起真正的併發請求了。性能優化

併發請求操做流程示意圖以下:
服務器

此處設置了一道門,以保證全部線程能夠同時生效。可是,此處的同時啓動,也只是語言層面的東西,也並不是絕對的同時併發。具體的調用還要依賴於CPU個數,線程數及操做系統的線程調度功能等,不過我們也無需糾結於這些了,重點在於理解原理!架構

與 CountDownLatch 有相似功能的,還有個工具柵欄 CyclicBarrier, 也是提供一個等待全部線程到達某一點後,再一塊兒開始某個動做,效果一致,不過柵欄的目的確實比較純粹,就是等待全部線程到達,而前面說的閉鎖 CountDownLatch 雖然實現的也是全部線程到達後再開始,可是他的觸發點實際上是 最後那一個開關,因此側重點是不同的。

簡單看一下柵欄是如何實現真正同時併發呢?示例以下:併發

// 與 閉鎖 結構一致
public class LatchTest {

    public static void main(String[] args) throws InterruptedException {

        Runnable taskTemp = new Runnable() {

            private int iCounter;

            @Override
            public void run() {
                // 發起請求
//              HttpClientOp.doGet("https://www.baidu.com/");
                iCounter++;
                System.out.println(System.nanoTime() + " [" + Thread.currentThread().getName() + "] iCounter = " + iCounter);
            }
        };

        LatchTest latchTest = new LatchTest();
//        latchTest.startTaskAllInOnce(5, taskTemp);
        latchTest.startNThreadsByBarrier(5, taskTemp);
    }

    public void startNThreadsByBarrier(int threadNums, Runnable finishTask) throws InterruptedException {
        // 設置柵欄解除時的動做,好比初始化某些值
        CyclicBarrier barrier = new CyclicBarrier(threadNums, finishTask);
        // 啓動 n 個線程,與柵欄閥值一致,即當線程準備數達到要求時,柵欄恰好開啓,從而達到統一控制效果
        for (int i = 0; i < threadNums; i++) {
            Thread.sleep(100);
            new Thread(new CounterTask(barrier)).start();
        }
        System.out.println(Thread.currentThread().getName() + " out over...");
    }
}


class CounterTask implements Runnable {

    // 傳入柵欄,通常考慮更優雅方式
    private CyclicBarrier barrier;

    public CounterTask(final CyclicBarrier barrier) {
        this.barrier = barrier;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " is ready...");
        try {
            // 設置柵欄,使在此等待,到達位置的線程達到要求便可開啓大門
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " started...");
    }
}

其運行結果以下圖:app

各有其應用場景吧,關鍵在於需求。就本文示例的需求來講,我的更願意用閉鎖一點,由於更可控了。可是代碼倒是多了,因此看你喜歡吧!

免費獲取更多安卓開發架構的資料(包括Fultter、高級UI、性能優化、架構師課程、 NDK、Kotlin、混合式開發(ReactNative+Weex)和一線互聯網公司關於android面試的題目彙總能夠加入【騰訊@安卓中高級進階】

相關文章
相關標籤/搜索