使用 java.util.concurrent.Callable java
public static void main(String[] args){ FutureTask<Integer> task = new FutureTask<>(new MyTask()); task.run(); try { task.get(); //這裏是阻塞的,直到 mytask運行完成 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } static class MyTask implements Callable<Integer>{ /** Computes a result, or throws an exception if unable to do so. @return computed result @throws Exception if unable to compute a result */ @Override public Integer call() throws Exception { System.out.println("start"); return 1; } }
咱們線程經常使用的是繼承 Runable 。這是沒有返回值的。可是Callable 有返回值,並且有異常拋出ide
使用 java.util.concurrent.ForkJoinTaskthis
public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("-----------main being---------------"); ForkJoinPool forkJoinPool = new ForkJoinPool(); MyTask myTask = new MyTask("mainTask"); forkJoinPool.submit(myTask); System.out.println(myTask.get()); System.out.println("-----------main end---------------"); } static class MyTask extends RecursiveTask<Integer> { private String name; public MyTask(String name) { this.name = name; } /** The main computation performed by this task. @return the result of the computation */ @Override protected Integer compute() { if ("leftTask".equals(name) || "rightTask".equals(name)) { System.out.println("begin: 【" + name + "】"); try { Thread.sleep(2000L); } catch (InterruptedException e) { // } System.out.println("end: 【" + name + "】"); return 1; } MyTask leftTask = null; MyTask rightTask = null; if ("mainTask".equals(name)) { System.out.println("begin: 【" + name + "】"); leftTask = new MyTask("leftTask"); rightTask = new MyTask("rightTask"); leftTask.fork(); rightTask.fork(); System.out.println("end: 【" + name + "】"); } return rightTask.join() + leftTask.join(); }
RecursiveTask 是有返回值的, RecursiveAction 是沒有返回值的線程