多线程模拟测试网站并发性

网站开发完了后,需要测试网站能支持多少用户并发访问,下面的java代码可以产生多条线程,模拟多个用户同时访问网站,以测试网站的并发性能。

 

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpConnection {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		//测试的网站URL
		final URL url=new URL("http://www.baidu.com");
		//并发数量
		final int concurrentNum=100;
        ExecutorService pool=  Executors.newCachedThreadPool();
        for (int i = 0; i < concurrentNum; i++) {
        	pool.execute(new Runnable() {
				
				@Override
				public void run() {
					try {
						while(true){
							URLConnection connection= url.openConnection();
							InputStream inStream= connection.getInputStream();
							byte [] buff=new byte[1024];
							int len=-1;
							while((len=inStream.read(buff))!=-1){
								try {
									Thread.sleep(10);
									System.out.println(new String(buff,0,len));
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
								
							}
						}
                        
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				}
			});
        	
		}
	}

}

 

 

 

你可能感兴趣的:(java,thread,并发,网站)