溫馨提示×

java多線程怎么獲取返回值

小億
598
2024-05-15 19:28:28
欄目: 編程語言

在Java多線程中獲取返回值可以通過以下幾種方式實現:

  1. 使用Callable和Future接口:Callable接口表示一個可以返回結果的任務,Future接口表示一個可能還沒有完成的任務的結果??梢酝ㄟ^ExecutorService.submit(Callable)方法提交Callable任務,并返回一個Future對象,然后可以通過Future.get()方法獲取任務的返回值。
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();
  1. 使用Thread.join()方法:通過調用Thread.join()方法,主線程可以等待子線程執行完畢并獲取其返回值。
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        // 執行耗時操作
    }
});
thread.start();
thread.join();
// 獲取返回值
  1. 使用共享變量:可以使用共享變量在多個線程之間傳遞數據。在需要返回值的地方,可以將值保存到共享變量中,然后在另一個線程中獲取這個值。
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);

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女