阅读量:0
Java中获取线程返回值的常用方法有以下几种:
- 使用Callable接口和Future对象:创建一个Callable对象,并使用ExecutorService的submit方法提交该任务,返回一个Future对象。然后可以通过调用Future对象的get方法来获取线程的返回值。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> future = executor.submit(new MyCallable()); try { int result = future.get(); System.out.println("线程返回值:" + result); } catch (Exception e) { e.printStackTrace(); } finally { executor.shutdown(); } } } class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { // 执行耗时任务,返回结果 return 100; } }
- 继承Thread类并重写run方法:通过继承Thread类并重写run方法,在执行耗时任务后,可以通过定义一个成员变量来保存返回值,然后通过调用该线程对象的join方法来等待线程执行结束,并获取返回值。
public class Main { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); try { myThread.join(); // 等待线程执行结束 int result = myThread.getResult(); System.out.println("线程返回值:" + result); } catch (InterruptedException e) { e.printStackTrace(); } } } class MyThread extends Thread { private int result; @Override public void run() { // 执行耗时任务 result = 100; } public int getResult() { return result; } }
- 使用FutureTask类:可以将Callable对象作为参数传递给FutureTask类的构造方法,然后通过调用FutureTask对象的get方法来获取线程的返回值。
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Main { public static void main(String[] args) { FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable()); Thread thread = new Thread(futureTask); thread.start(); try { int result = futureTask.get(); System.out.println("线程返回值:" + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { // 执行耗时任务,返回结果 return 100; } }
这些方法都可以用来获取线程的返回值,选择哪种方法取决于实际需求和场景。