在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);
這些是一些常見的方法,在實際開發中可以根據具體情況選擇最適合的方式來獲取多線程的返回值。