JAVA 线程返回值

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


/**
* Runnable是执行工作的独立任务,但是它不返回任何值,
* 如果希望任务在完成时能够返回一个值,可以实现Callable接口
* @Date 2010-12-6
* @version [版本号]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class PrimeThread
{

public static void main(String[] args) throws Exception
{
ExecutorService service = Executors.newCachedThreadPool();
System.out.println("=="+service.submit(new TaskResult(66)).get().toString());
}
}

class TaskResult implements Callable<String>
{
private int id;

public TaskResult(int id)
{
this.id = id;
}

public String call() throws Exception
{
return "result of TaskWithResult " + id;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java实现线程返回值的方法有多种。其中一种方法是通过继承Thread类或者实现Runnable接口,在子线程中设置共享变量来获取返回值。这种方法的缺点是不能精确判断子线程是否执行完成。另一种方法是通过实现Callable接口,使用FutureTask启动子线程,然后使用FutureTask的get()方法获取返回值。这种方法可以精确地获取返回值。 以下是两种方法的示例代码: 方法一,通过设置共享变量获取返回值: ```java public class TestThread extends Thread { public String value = null; @Override public void run() { System.out.println("TestThread start...."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("TestThread end"); value = "TestThread"; } } public class Main { public static void main(String[] args) throws InterruptedException { TestThread thread = new TestThread(); thread.start(); while (thread.value == null) { Thread.sleep(100); } System.out.println(thread.value); } } ``` 方法二,使用Callable和FutureTask获取返回值: ```java import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class TestCallable implements Callable<String> { @Override public String call() throws Exception { System.out.println("TestCallable start...."); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("TestCallable end"); return "TestCallable"; } } public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<String> futureTask = new FutureTask<>(new TestCallable()); Thread thread = new Thread(futureTask); thread.start(); String value = futureTask.get(); System.out.println(value); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值