多執行緒學習---Callable和Future的使用(十)
阿新 • • 發佈:2018-11-03
1.Callable和Future適用於帶有返回結果的多執行緒
示例
public class CallAndFutureStudy { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> result = threadPool.submit(new Callable<String>( ) { @Override public String call() throws Exception { Thread.sleep(2000); return "hello"; } }); System.out.println("等待輸出結果"); try { System.out.println("取出返回結果:"+result.get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2.CompletionService(提交一組Callable)
處理多個帶有返回結果的執行緒
public class CallAndFutureStudy { public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(10); CompletionService<String> completionService = new ExecutorCompletionService<String>(threadPool); for(int i = 0;i < 10;i++){ final int seq = i; completionService.submit(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(new Random().nextInt(2000)); return "ThreadName"+Thread.currentThread().getName()+"執行,返回結果:"+seq; } }); } for(int i = 0;i < 10;i++){ try { System.out.println(completionService.take().get()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
執行結果: