线程 - 带返回值的多线程

本文介绍如何在Java中使用Callable接口和Future对象来创建带有返回值的线程,通过示例代码展示了如何利用ExecutorService线程池提交Callable任务并获取其返回结果。

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

之前我们使用多线程要么是继承Thread类,要么是实现Runnable接口,然后重写一下run()方法即可。

但是只有的话如果有死锁、对共享资源的访问和随时监控线程状态就不行了,于是在Java5之后就有了Callable接口。

简单实现带返回值的线程

代码如下:CallableFuture类

package com.test.thread;
 
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class CallableFuture {
	public static void main(String[] args) {
		
		//创建一个线程池
		ExecutorService pool = Executors.newFixedThreadPool(3) ;
		
		//创建三个有返回值的任务
		CallableTest callableTest1 = new CallableTest("我是线程1") ;
		CallableTest callableTest2 = new CallableTest("我是线程2") ;
		CallableTest callableTest3 = new CallableTest("我是线程3") ;
		
		Future future1 = pool.submit(callableTest1) ;
		Future future2 = pool.submit(callableTest2) ;
		Future future3 = pool.submit(callableTest3) ;
		
		try {
			System.out.println(future1.get().toString());
			System.out.println(future2.get().toString());
			System.out.println(future3.get().toString());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}finally{
			pool.shutdown();
		}
		
	}
}

代码如下:CallableTest类

package com.test.thread;
 
import java.util.concurrent.Callable;
 
public class CallableTest implements Callable {
	
	private String threadName ;
	
	public CallableTest(String threadName) {
		this.threadName = threadName;
	}

	@Override
	public Object call() throws Exception {
		return threadName+"返回的信息";
	}
}

运行结果

我是线程1返回的信息
我是线程2返回的信息
我是线程3返回的信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陆克和他的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值