多线程七

来源:互联网 发布:如何看淘宝价格走势 编辑:程序博客网 时间:2024/06/11 05:45
利用Callable&Future创建线程
问题:
         之前遇到的的执行任务都是run方法实现的任务,而run方法是没有返回值的,我们并不知道线程什么时候执行结束。

解决途径 :

         如果线程执行结束之后能返回一个值,那么我们就知道线程已经之行结束了



public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();//Callable<T>  泛型的具体类型就是返回值的类型  也决定了Future泛型类型Future<Integer> future = threadPool.submit(new Callable<Integer>() {@Overridepublic Integer call() throws Exception {System.out.println("任务开始");Thread.sleep(3000);System.out.println("任务结束");return 10;}});int value = 0;try {value = future.get();} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}System.out.println(value);}








0 0