Java中获取线程返回值的常用方法有以下几种:
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;
}
}
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;
}
}
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;
}
}
这些方法都可以用来获取线程的返回值,选择哪种方法取决于实际需求和场景。