共計(jì) 1068 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Java 多線程中獲取返回值可以通過以下幾種方式實(shí)現(xiàn):
- 使用 Callable 和 Future 接口:Callable 接口表示一個(gè)可以返回結(jié)果的任務(wù),F(xiàn)uture 接口表示一個(gè)可能還沒有完成的任務(wù)的結(jié)果。可以通過 ExecutorService.submit(Callable) 方法提交 Callable 任務(wù),并返回一個(gè) Future 對象,然后可以通過 Future.get() 方法獲取任務(wù)的返回值。
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.join() 方法:通過調(diào)用 Thread.join() 方法,主線程可以等待子線程執(zhí)行完畢并獲取其返回值。
Thread thread = new Thread(new Runnable() {@Override
public void run() {// 執(zhí)行耗時(shí)操作
}
});
thread.start();
thread.join();
// 獲取返回值
- 使用共享變量:可以使用共享變量在多個(gè)線程之間傳遞數(shù)據(jù)。在需要返回值的地方,可以將值保存到共享變量中,然后在另一個(gè)線程中獲取這個(gè)值。
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);
這些是一些常見的方法,在實(shí)際開發(fā)中可以根據(jù)具體情況選擇最適合的方式來獲取多線程的返回值。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完