ExecutorService 并发性能测试

	// 公共线程池
	private ExecutorService executorService = Executors.newFixedThreadPool(3);;

	// 测试不使用线程池,响应时间
	public void test1() throws InterruptedException {
		// 每个请求耗时20s,300个请求20s左右全部返回
		for (int i = 0; i < 20; i++) {
			Thread.sleep(1000);
			System.out.println("future.get = " + i);
		}
	}

	// 测试每个请求使用创建自己的线程池,响应时间
	public void test2() throws InterruptedException, ExecutionException {
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		/* 线程池总线程数3,每个线程耗时1s,一个请求需要20个线程,300个请求需要7~9s左右完成! */

		List<Future<String>> futures = new ArrayList<Future<String>>();
		for (int i = 0; i < 20; i++) {
			Future<String> future = executorService.submit(new TaskWithResult(i));
			futures.add(future);
		}

		for (Future<String> future : futures) {
			System.out.println("future.get = " + future.get());
		}
		executorService.shutdown();
	}

	// 测试每个请求使用公共的线程池,响应时间
	public void test3() throws InterruptedException, ExecutionException {
		// 公共线程池总线程数3,每个线程耗时1s,一个请求需要20个线程,300个请求需要35分钟左右完成(每个请求7s左右)

		List<Future<String>> futures = new ArrayList<Future<String>>();
		for (int i = 0; i < 20; i++) {
			Future<String> future = executorService.submit(new TaskWithResult(i));
			futures.add(future);
		}

		for (Future<String> future : futures) {
			System.out.println("future.get = " + future.get());
		}
	}

	class TaskWithResult implements Callable<String> {
		private int id;

		public TaskWithResult(int id) {
			this.id = id;
		}

		@Override
		public String call() throws Exception {
			Thread.sleep(1000);
			return String.valueOf(id);
		}
	}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 我行我“速” 设计师:Amelia_0503 返回首页