在Java多线程中获取返回值可以通过以下几种方式实现:
ExecutorService executor = Executors.newFixedThreadPool(1);
Callable<Integer> task = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 1 + 2;
}
};
Future<Integer> future = executor.submit(task);
Integer result = future.get();
System.out.println("Result: " + result);
executor.shutdown();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 执行耗时操作
}
});
thread.start();
thread.join();
// 获取返回值
class MyRunnable implements Runnable {
private int result;
@Override
public void run() {
result = 1 + 2;
}
public int getResult() {
return result;
}
}
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
thread.join();
int result = myRunnable.getResult();
System.out.println("Result: " + result);
这些是一些常见的方法,在实际开发中可以根据具体情况选择最适合的方式来获取多线程的返回值。