繁体   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