java concurrent之Runnable,Callable,Executor

本文介绍了Java中Callable接口如何用于创建返回结果的任务,并通过FutureTask和ExecutorService执行这些任务。对比Runnable,Callable提供了更丰富的功能。

Runnable作为线程的接口已经广为大家所知。

但是在执行任务的时候如果想要返回结果怎么办?如果想抛出异常怎么办?

这些都是Runnable无法做到的。这时候另一个线程接口就出现了: Callable:

 V call() throws Exception;

 Oh,perfect! 可以返回值,可以抛异常!

 

我们知道Runnable是通过Thread 类来执行的:new Thread(new Runnable(){..}).start();

那么Callable呢?

这个是通过RunnableFuture来执行的(当然RunnableFuture也可以用来执行Runnable)。

RunnableFuture的一个常用子类是:FutureTask.

下面的代码演示了这几个接口的用法:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;


@SuppressWarnings("unchecked")
public class TestTask {
private FutureTask<String> task=new FutureTask(new Callable(){
	public String call() throws Exception {
		return "hello";
	}
}
);
private ExecutorService exeService=Executors.newFixedThreadPool(4);
public static void main(String args[]){
	TestTask test=new TestTask();
	test.testFuture();
	test.testExecutor();
}
public void testFuture(){
	task.run();
	String result="";
	try {
		result = task.get();
	} catch (InterruptedException e) {
		e.printStackTrace();
	} catch (ExecutionException e) {
		e.printStackTrace();
	}
	System.out.println("task returns :"+result);
}
public void testExecutor(){
	exeService.execute(task);
	String result="";
	try {
		result = task.get();
	} catch (InterruptedException e) {
		e.printStackTrace();
	} catch (ExecutionException e) {
		e.printStackTrace();
	}
	System.out.println("task submmited and run:"+result);
}
}

 细心的看官可能已经发现了,这里面用到了另一个类:ExecutorService.

 这是java concurrent执行框架的一部分。

 这个框架包含了Executor(能执行Runnable),ExecutorService(Executor的子类,加强了对Runnable生命周期的管理),Executors(Executor和ExecutorService的工厂方法).在上面是通过Executors的静态方法产生一个

ThreadPoolExecutor来执行Runnable.

Java 多线程编程中,`Runnable` 接口是一个基础的多线程任务定义接口,其定义为 `public interface Runnable { public abstract void run(); }`,实现该接口的类需要重写 `run` 方法,且该方法没有返回值,通常在创建线程时,会将 `Runnable` 对象传递给 `Thread` 以便执行[^1]。 而 `Callable` 接口与 `Runnable` 相比,具有显著的优势。`Callable` 接口定义的方法为 `V call() throws Exception;`,它允许任务返回一个结果(泛型 `V`),并且可以抛出异常。这意味着使用 `Callable` 可以在多线程任务执行完成后获取其执行结果,而 `Runnable` 的 `run` 方法没有返回值,无法直接获取任务执行的结果。例如,在需要多线程计算并汇总结果的场景中,使用 `Callable` 可以方便地获取每个线程计算的结果,然后进行汇总。以下是一个简单的示例代码: ```java import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class CallableExample { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(3); List<Future<Integer>> futures = new ArrayList<>(); // 提交 Callable 任务 for (int i = 0; i < 3; i++) { Callable<Integer> task = () -> { // 模拟耗时操作 Thread.sleep(1000); return 10 * (int) (Math.random() * 10); }; futures.add(executor.submit(task)); } // 获取结果 int sum = 0; for (Future<Integer> future : futures) { sum += future.get(); } System.out.println("汇总结果: " + sum); executor.shutdown(); } } ``` 在上述代码中,通过 `ExecutorService` 提交 `Callable` 任务,使用 `Future` 对象获取任务的执行结果,最后将结果汇总。 此外,`Callable` 可以更好地处理异常。`call` 方法可以抛出异常,调用者可以捕获并处理这些异常,而 `Runnable` 的 `run` 方法不能抛出受检查的异常,异常处理相对受限。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值