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> futures = new ArrayList>();
		for (int i = 0; i < 20; i++) {
			Future future = executorService.submit(new TaskWithResult(i));
			futures.add(future);
		}

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

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

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

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

	class TaskWithResult implements Callable {
		private int id;

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

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

 

你可能感兴趣的:(java,thread,线程池)