最大線程數開到100個沒有問題
大於101個就有很多連接失敗的
初步判斷是tomcat的最大連接數設置的問題
重新設置tomcat server.xml
acceptCount=200後,最大線程可開到150 沒有任何錯誤
acceptCount 指定放在隊列裡的請求數
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" acceptCount="200" />
Java代碼
package com.ask.pressure;
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.URL;
public class AskPressure {
private static String url = "http://192.168.0.59:8080/ask/index.html";
private static Integer error = 0;
private static Integer threads = 150;
private static Long startTime;
public static void main(String[] args) {
WorkThread[] workThreads = new WorkThread[threads];
for(int i = 0; i < threads; i++){
workThreads[i] = new WorkThread();
}
startTime = System.currentTimeMillis();
//System.out.printf("線程數組初始化耗時%d毫秒\n", (System.currentTimeMillis() - startTime));
for(int i = 0; i < threads; i++){
workThreads[i].start();
}
//System.out.printf("連接失敗:%d",error);
}
private static class WorkThread extends Thread {
public void run(){
long start = System.currentTimeMillis();
long end = 0;
try {
URL u = new URL(url);
HttpURLConnection urlConn = (HttpURLConnection) u.openConnection();
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-type","text/html; charset=UTF-8");
urlConn.connect();
//System.out.printf( "小博士頁面編碼: % s\n",urlConn.getContentEncoding());
InputStream is = urlConn.getInputStream();
StringBuffer buffer = new StringBuffer();
readToBuffer(buffer,is);
end = System.currentTimeMillis();
} catch (Exception e) {
synchronized(error){
error ++;
}
e.printStackTrace();
}
synchronized(threads){
threads --;
System.out.printf("還有%d個未完線程,耗時%d毫秒\n",threads, (System.currentTimeMillis() - startTime));
if(threads == 0){
System.out.printf("總耗時:%d毫秒\n", (System.currentTimeMillis() - startTime));
System.out.printf("連接失敗:%d\n",error);
}
}
}
public void readToBuffer(StringBuffer buffer,InputStream is)
throws IOException {
String line; // 用來保存每行讀取的內容
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
line = reader.readLine(); // 讀取第一行
while (line != null) { // 如果line為空說明讀完了
buffer.append(line); // 將讀到的內容添加到buffer中
buffer.append("\n"); // 添加換行符
line = reader.readLine(); // 讀取下一行
}
}
}
}
還有9個未完線程,耗時1484毫秒
還有5個未完線程,耗時1547毫秒
還有6個未完線程,耗時1516毫秒
還有7個未完線程,耗時1516毫秒
還有8個未完線程,耗時1484毫秒
還有4個未完線程,耗時1547毫秒
還有3個未完線程,耗時1547毫秒
還有2個未完線程,耗時1563毫秒
還有1個未完線程,耗時1578毫秒
總耗時:1578毫秒
連接失敗:0
還有0個未完線程,耗時1578毫秒
總耗時:1578毫秒
連接失敗:0