中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Java中如何模擬真正的同時(shí)并發(fā)請(qǐng)求?

2018-10-08    來(lái)源:importnew

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

有時(shí)需要測(cè)試一下某個(gè)功能的并發(fā)性能,又不要想借助于其他工具,索性就自己的開(kāi)發(fā)語(yǔ)言,來(lái)一個(gè)并發(fā)請(qǐng)求就最方便了。

Java 中模擬并發(fā)請(qǐng)求,自然是很方便的,只要多開(kāi)幾個(gè)線程,發(fā)起請(qǐng)求就好了。但是,這種請(qǐng)求,一般會(huì)存在啟動(dòng)的先后順序了,算不得真正的同時(shí)并發(fā)!怎么樣才能做到真正的同時(shí)并發(fā)呢?是本文想說(shuō)的點(diǎn),Java 中提供了閉鎖 CountDownLatch, 剛好就用來(lái)做這種事就最合適了。

只需要:

  1. 開(kāi)啟n個(gè)線程,加一個(gè)閉鎖,開(kāi)啟所有線程;
  2. 待所有線程都準(zhǔn)備好后,按下開(kāi)啟按鈕,就可以真正的發(fā)起并發(fā)請(qǐng)求了。
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++) {
                    // 發(fā)起請(qǐng)求
//                    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 {
                        // 使線程在此等待,當(dāng)開(kāi)始門打開(kāi)時(shí),一起涌入門中
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            // 將結(jié)束門減1,減到0時(shí),就可以開(kāi)啟結(jié)束門了
                            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...");
        // 因開(kāi)啟門只需一個(gè)開(kāi)關(guān),所以立馬就開(kāi)啟開(kāi)始門
        startGate.countDown();
        // 等等結(jié)束門開(kāi)啟
        endGate.await();
        long endTime = System.nanoTime();
        System.out.println(endTime + " [" + Thread.currentThread() + "] All thread is completed.");
        return endTime - startTime;
    }
}

其執(zhí)行效果如下圖所示:

HttpClientOp? 工具類,可以使用 成熟的工具包,也可以自己寫(xiě)一個(gè)簡(jiǎn)要的訪問(wèn)方法,參考如下:

class HttpClientOp {
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回結(jié)果字符串
        try {
            // 創(chuàng)建遠(yuǎn)程url連接對(duì)象
            URL url = new URL(httpurl);
            // 通過(guò)遠(yuǎn)程url連接對(duì)象打開(kāi)一個(gè)連接,強(qiáng)轉(zhuǎn)成httpURLConnection類
            connection = (HttpURLConnection) url.openConnection();
            // 設(shè)置連接方式:get
            connection.setRequestMethod("GET");
            // 設(shè)置連接主機(jī)服務(wù)器的超時(shí)時(shí)間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設(shè)置讀取遠(yuǎn)程返回的數(shù)據(jù)時(shí)間:60000毫秒
            connection.setReadTimeout(60000);
            // 發(fā)送請(qǐng)求
            connection.connect();
            // 通過(guò)connection連接,獲取輸入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封裝輸入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放數(shù)據(jù)
                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 {
            // 關(guān)閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

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

            connection.disconnect();// 關(guān)閉遠(yuǎn)程連接
        }

        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);
            // 通過(guò)遠(yuǎn)程url連接對(duì)象打開(kāi)連接
            connection = (HttpURLConnection) url.openConnection();
            // 設(shè)置連接請(qǐng)求方式
            connection.setRequestMethod("POST");
            // 設(shè)置連接主機(jī)服務(wù)器超時(shí)時(shí)間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設(shè)置讀取主機(jī)服務(wù)器返回?cái)?shù)據(jù)超時(shí)時(shí)間:60000毫秒
            connection.setReadTimeout(60000);

            // 默認(rèn)值為:false,當(dāng)向遠(yuǎn)程服務(wù)器傳送數(shù)據(jù)/寫(xiě)數(shù)據(jù)時(shí),需要設(shè)置為true
            connection.setDoOutput(true);
            // 默認(rèn)值為:true,當(dāng)前向遠(yuǎn)程服務(wù)讀取數(shù)據(jù)時(shí),設(shè)置為true,該參數(shù)可有可無(wú)
            connection.setDoInput(true);
            // 設(shè)置傳入?yún)?shù)的格式:請(qǐng)求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 設(shè)置鑒權(quán)信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            // 通過(guò)連接對(duì)象獲取一個(gè)輸出流
            os = connection.getOutputStream();
            // 通過(guò)輸出流對(duì)象將參數(shù)寫(xiě)出去/傳輸出去,它是通過(guò)字節(jié)數(shù)組寫(xiě)出的
            os.write(param.getBytes());
            // 通過(guò)連接對(duì)象獲取一個(gè)輸入流,向遠(yuǎn)程讀取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 對(duì)輸入流對(duì)象進(jìn)行包裝:charset根據(jù)工作項(xiàng)目組的要求來(lái)設(shè)置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循環(huán)遍歷一行一行讀取數(shù)據(jù)
                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 {
            // 關(guān)閉資源
            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();
                }
            }
            // 斷開(kāi)與遠(yuǎn)程地址url的連接
            connection.disconnect();
        }
        return result;
    }
}

如上,就可以發(fā)起真正的并發(fā)請(qǐng)求了。

并發(fā)請(qǐng)求操作流程示意圖如下:

此處設(shè)置了一道門,以保證所有線程可以同時(shí)生效。但是,此處的同時(shí)啟動(dòng),也只是語(yǔ)言層面的東西,也并非絕對(duì)的同時(shí)并發(fā)。具體的調(diào)用還要依賴于CPU個(gè)數(shù),線程數(shù)及操作系統(tǒng)的線程調(diào)度功能等,不過(guò)咱們也無(wú)需糾結(jié)于這些了,重點(diǎn)在于理解原理!

與 CountDownLatch 有類似功能的,還有個(gè)工具柵欄 CyclicBarrier, 也是提供一個(gè)等待所有線程到達(dá)某一點(diǎn)后,再一起開(kāi)始某個(gè)動(dòng)作,效果一致,不過(guò)柵欄的目的確實(shí)比較純粹,就是等待所有線程到達(dá),而前面說(shuō)的閉鎖 CountDownLatch 雖然實(shí)現(xiàn)的也是所有線程到達(dá)后再開(kāi)始,但是他的觸發(fā)點(diǎn)其實(shí)是最后那一個(gè)開(kāi)關(guān),所以側(cè)重點(diǎn)是不一樣的。

簡(jiǎn)單看一下柵欄是如何實(shí)現(xiàn)真正同時(shí)并發(fā)呢?示例如下:

// 與 閉鎖 結(jié)構(gòu)一致
public class LatchTest {

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

        Runnable taskTemp = new Runnable() {

            private int iCounter;

            @Override
            public void run() {
                // 發(fā)起請(qǐng)求
//              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 {
        // 設(shè)置柵欄解除時(shí)的動(dòng)作,比如初始化某些值
        CyclicBarrier barrier = new CyclicBarrier(threadNums, finishTask);
        // 啟動(dòng) n 個(gè)線程,與柵欄閥值一致,即當(dāng)線程準(zhǔn)備數(shù)達(dá)到要求時(shí),柵欄剛好開(kāi)啟,從而達(dá)到統(tǒng)一控制效果
        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 {

    // 傳入柵欄,一般考慮更優(yōu)雅方式
    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 {
            // 設(shè)置柵欄,使在此等待,到達(dá)位置的線程達(dá)到要求即可開(kāi)啟大門
            barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " - " + System.currentTimeMillis() + " started...");
    }
}

其運(yùn)行結(jié)果如下圖:

各有其應(yīng)用場(chǎng)景吧,關(guān)鍵在于需求。就本文示例的需求來(lái)說(shuō),個(gè)人更愿意用閉鎖一點(diǎn),因?yàn)楦煽亓恕5谴a卻是多了,所以看你喜歡吧!

標(biāo)簽: 安全 代碼 服務(wù)器

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:Java中JNI的使用(上)

下一篇:Ubuntu下面MySQL的參數(shù)文件my.cnf淺析