簡體   English   中英

Java:僅限於方法的線程之間的通信

[英]Java: Communication between threads restricted to a method

我必須創建一種方法來計算數組中所有元素的總和。 需要注意的是,將數組划分為多個線程的多個部分,以同時計算這些部分,然后合並以計算總和

所有這些都限於方法代碼內部。 問題是當我寫:

Thread t = new Thread(()->{
                int sum=0;
                //do some calculations
                //time to pass this result back to the main method
            });

本地匿名類只能訪問main方法的最終或有效的最終局部變量,這意味着我無法創建局部變量,然后更改它以更新結果。 我想不出一種方法來將線程的結果傳遞回去與其他線程的結果合並。

有什么辦法解決這個問題?

您可以在主線程中划分工作,然后執行以下操作:

 public class Foo implements Runnable {
     private volatile CustomArray<Integer> arr;
     private volatile Integer sum;

     public Foo(CustomArray<Integer> arr) {
         this.arr = arr;
     }

     @Override
     public void run() {
        synchronized(this.arr) {
            sum = arr.getSum();
        }
     }

     public Integer getValue() {
         synchronized(this.arr) {
             return sum;
         }
     }
 }

並從另一個線程調用,如下所示:

CustomArray<Integer> completeArray = new CustomArray<>(data);
ArrayList<CustomArray<Integer>> dividedArrays = completeArray.divideWork();

for(CustomArray<Integer> each : dividedArrays) {
    Foo foo = new Foo(each);
    new Thread(foo).start();

    // ... join through some method

    Integer value = foo.getValue();
}

或者,您可以使用ExecutorCallable

public void test() throws InterruptedException, ExecutionException
    {   
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() {
                return 2;
            }
        };
        Future<Integer> future = executor.submit(callable);

        // returns 2 or raises an exception if the thread dies
        Integer output = future.get();

        executor.shutdown();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM