Runnable接口和Callable接口有什么不同呢?
下文笔者将讲述Runnable接口和Callable接口的不同之处,如下所示:
多线程返回值的实验
两者的主要区别在返回值上: Runnable接口中的run()方法的返回值是void Callable接口中的call()方法是有返回值的,是一个泛型,和Future、FutureTask配合可以用来获取异步执行的结果例:
多线程返回值的实验
package com.java265.other; import java.util.Arraylist; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test6 { public static void main(String[] args) throws Exception { final CountDownLatch latch = new CountDownLatch(5); ExecutorService pool=Executors.newFixedThreadPool(5); List list=new ArrayList(); try { for(int j=0;j<5;j++){ Callable<Map<String, Integer>> c1 = new CallableThread(j,latch); Future<Map<String,Integer>> f1=pool.submit(c1); list.add(f1); } latch.await(); for(int i=0;i<list.size();i++){ Future<Map<String,Integer>> f1=(Future<Map<String, Integer>>) list.get(i); System.out.println((Integer) f1.get().get("info")); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } class CallableThread implements Callable<Map<String, Integer>> { //传递进来的参数 int data; private Map <String,Integer> map =new HashMap <String,Integer>();//定义需要返回的map private final CountDownLatch latch ; public CallableThread( int data, CountDownLatch latch) { this.data = data; this.latch = latch; } public Map<String,Integer> call() throws Exception { try{ // 每个参数手动增加88 data += 88; map.put("info", data); System.out.println("线程:"+Thread.currentThread().getName()); }catch(Exception e){ e.printStackTrace(); }finally{ latch.countDown(); } return map; } } ------运行以上代码,将输出以下信息---- 线程:pool-1-thread-3 线程:pool-1-thread-5 线程:pool-1-thread-2 线程:pool-1-thread-1 线程:pool-1-thread-4 88 89 90 91 92
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。