Callable接口和Runnable接口

本文对比了Java中Callable和Runnable接口的区别,详细介绍了两者在返回值、异常处理方面的不同,并通过示例代码展示了如何使用Callable来创建有返回值的任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Callable接口和Runnable接口相似,区别就是Callable需要实现call方法,而Runnable需要实现run方法;并且,call方法有返回值。

 

Runnable是执行工作的独立任务,不具有返回值。在Java SE5中引入的Callable是一种具有;类型参数的泛型,参数类型为从方法call()中返回的值,并且必须使用ExecutorService.submit()调用它。


Runnable和Callable都是接口
不同之处:
1.Callable可以返回一个类型V,而Runnable不可以
2.Callable能够抛出checked exception,而Runnable不可以。
Callable的源码如下:

public interface Callable {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

Runnable的源码如下:
public interface Runnable {
    /**
     * When an object implementing interface Runnable is used
     * to create a thread, starting the thread causes the object's
     * run method to be called in that separately executing
     * thread.
     * 

* The general contract of the method run is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run(); }


案例:

import java.util.*;
import java.util.concurrent.*;

public class CallableDemo {
	
	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		ArrayList> listResult = new ArrayList>();
		
		for (int i = 0; i < 5; i++) {
			listResult.add(exec.submit(new Calls(i)));
		}
		
		for(Future fs:listResult)
			try {
				System.out.println(fs.get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

}
class Calls implements Callable{

	private int id;
	public Calls() {
	}
	public Calls(int id) {
		this.id = id;
	}
	@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		return "the current id is: "+this.id;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值