线程之Callable,Future,CompletionService
import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadCallAndFuture { /** * 线程的返回值 */ public static void main(String[] args) { /* * 一个线程调用另一个线程的返回值 * 要想拿到返回值的这个过程需要等待 */ // ExecutorService executorService = Executors.newSingleThreadExecutor(); // Future<String> future = executorService.submit(new Callable<String>(){ // // @Override // public String call() throws Exception { // Thread.sleep(1000); // return "hello word"; // } // // }); // // System.out.println("waiting for result..."); // try { // System.out.println("result is : "+future.get()); // } catch (InterruptedException e) { // e.printStackTrace(); // } catch (ExecutionException e) { // e.printStackTrace(); // } /* * 上例似乎在实际中是没太大的用处的 * 下例是一个收割事例 * 就好像有一些菜田,那个先熟,先收割那个 * 有一些线程,当那个线程有返回值就获得那个返回值 * CompletionService接口 */ ExecutorService executorService = Executors.newFixedThreadPool(10); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService); for(int i=0;i<10;i++){ final int flag = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return flag; } }); } for(int i=0;i<10;i++){ try { System.out.println(completionService.take().get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } }
huidaoli版权所有:转载请注明出处,谢谢合作!