Runnable接口和Callable接口有什么不同呢?

java面试王 Java面经 发布时间:2021-12-02 14:38:44 阅读数:14593 1
下文笔者将讲述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
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaMianJing/202112/16384271641985.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者