多线程获取返回值 - Future and CompletionService and Runnable

public class CompletionServiceTest {

	public static void main(String[] args) {
		CompletionServiceTest test = new CompletionServiceTest();
		try {
			test.getValueByFuture();
			test.getValueByCompletionService();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	public void getValueByFuture() throws InterruptedException, ExecutionException {
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<String> future = threadPool.submit(new ExeCall(),"success");
		
		System.out.println(future.get());//返回值是"success"
		threadPool.shutdown();
	}

	public void getValueByCompletionService() throws InterruptedException, ExecutionException  {
		int threadPoolSize = 10;
		ExecutorService threadPool = Executors.newFixedThreadPool(threadPoolSize);
		CompletionService<String> completionService = new ExecutorCompletionService<String>(threadPool);
		
		for (int i = 1; i <= threadPoolSize; i++) {
			Future<String> future = completionService.submit(new ExeCall(),"success");
			System.out.println(future.get());//返回值是"success"
		}
		
		threadPool.shutdown();
	}

	class ExeCall implements Runnable {

		@Override
		public void run() {
			Random ra = new Random();
			int num = ra.nextInt(100);
			System.out.println("Get a random number : " + num);
		}

	}
	
}

猜你喜欢

转载自margaret0071.iteye.com/blog/2347417