java 带返回值线程 Callable

本文介绍了一个使用Java 1.5特性的并发编程示例,包括FutureTask和Callable接口的具体应用。通过创建自定义的Ticket1类实现Callable接口,并在MyClass2中启动一个新的线程来执行Ticket1实例,展示如何获取异步任务的结果。

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

class Ticket1 implements Callable<Integer> {
	@Override
	public Integer call() throws Exception {
		System.out.println("调用到call");
		return 500;
	}
}
public class MyClass2 {

	public static void main(String[] args) {	
		//FutureTask继承了RunnableFuture  RunnableFuture继承了Runnable 所以在Thread 中可以直接传funturetask
		FutureTask futureTask = new FutureTask(new Ticket1());
		new Thread(futureTask).start();;
		try {
			System.out.println(futureTask.get());
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}	
	}
}
java 1.5以后有的新的写法
### JavaCallable 接口在多线程环境下的用法 #### Callable 接口简介 `Callable<V>` 是 `java.util.concurrent` 包中的一个泛型接口,它类似于 `Runnable` 接口,但是具有返回值并能抛出异常的能力。这使得它可以用于更复杂的场景。 ```java public interface Callable<V> { V call() throws Exception; } ``` 此接口定义了一个名为 `call()` 的方法,该方法可以有返回值并且能够声明抛出受检异常[^2]。 #### 创建和使用 Callable 对象 为了利用 `Callable` 接口,在实际应用中通常会将其与 `FutureTask` 或者直接提交给实现了 `ExecutorService` 接口的服务一起工作来获取计算的结果。 下面的例子展示了如何创建实现 `Callable<Integer>` 接口的任务实例: ```java import java.util.concurrent.Callable; class TaskWithResult implements Callable<Integer> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public Integer call() throws Exception { System.out.println("Executing Task With ID : " + id); Thread.sleep(1000); // Simulate work being done. return id * 2; // Return result of computation. } } ``` #### 提交任务到 ExecutorService 并获得 Future 结果 一旦有了上述类型的可调用对象之后,则可以通过如下方式向 `ExecutorService` 实例提交它们,并接收表示异步计算结果的 `Future` 类型的对象。 ```java import java.util.concurrent.*; public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> callable = new TaskWithResult(1); // Submitting the callable task to get a future object back which will hold the result once available. Future<Integer> future = executor.submit(callable); // Do other things while waiting for the result... try { if (!future.isDone()) { System.out.println("Waiting for the result..."); } // Get method blocks until the result is ready or timeout occurs. Integer result = future.get(); System.out.println("The Result Is: " + result); } finally { executor.shutdown(); // Always shutdown when finished using it. } } } ``` 这段代码片段说明了怎样通过 `submit(Callable<T>)` 方法把实现了 `Callable` 接口的任务交给由 `Executors` 工厂函数构建出来的单一线程池去执行;接着我们得到了一个 `Future<Integer>` 来代表这个操作可能产生的整数输出。最后一步是从 `Future` 获取最终结果,如果此时还没有完成则会被阻塞直到得到答案为止[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值