首先创建实现Callable的类,代码如下:
import java.util.concurrent.Callable; /** * Created by ea on 2017/3/13. */ public class TestCallable implements Callable<Integer> { private int[] arr; private int start, end; public TestCallable(int[] a, int start, int end) { arr = a; this.start = start; this.end = end; } public Integer call() { int ans = Integer.MIN_VALUE; for (int i = start; i < end; i++) { ans = Math.max(ans, arr[i]); } return ans; } } 然后在主程序中创建ExecutorService,提交任务,获取计算结果。 import java.util.concurrent.*; public class Main { public static void main(String[] args) { int[] a = {4, 5, 6, 1, 2, 3}; TestCallable call1 = new TestCallable(a, 0, a.length / 2); TestCallable call2 = new TestCallable(a, a.length / 2 + 1, a.length); ExecutorService s = Executors.newFixedThreadPool(3); Future<Integer> t1 = s.submit(call1); Future<Integer> t2 = s.submit(call2); try { int ans = Math.max(t1.get(), t2.get()); System.out.println("ans:" + ans); } catch(InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }