先用java實現HTTP訪問網頁
public class HttpCon {
public void Test(String url)
{
StringBuffer html=new StringBuffer();
URL url1=null;
URLConnection uc=null;
BufferedReader br=null;
InputStreamReader isr=null;
//創建URL對象
try {
//創建URL鏈接對象
url1= new URL(url);
//打開鏈接
uc= url1.openConnection();
//獲取輸入流
isr=new InputStreamReader(uc.getInputStream(), "utf-8");
//建立緩衝流
br=new BufferedReader(isr);
//建立臨時字符串
String temp =null;
while((temp=br.readLine())!=null)
{
html.append(temp);//將讀取的數據存入html中
}
System.out.println(html);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(isr!=null)
{
try {
isr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
寫一個用於訪問的線程
class MyThread extends Thread
{
public void run()
{
while(true)
{
new HttpCon().Test("URL");
}
}
}
在Main函數中調用啟動這個線程
public static void main(String[] args) {
MyThread mt=new MyThread();
mt.start();
}
我們來試試併發3000個線程
public static void main(String[] args) {
for(int i=0;i<3000;i++)
{
MyThread mt=new MyThread();
mt.start();
}
}
閱讀更多 騎著豬豬的CodeMonkey 的文章