简体   繁体   English

Java:仅限于方法的线程之间的通信

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

I have to create a method to calculate the sum of all elements in an array. 我必须创建一种方法来计算数组中所有元素的总和。 The caveat is that the array is divided into a number of parts for many threads to calculate these parts simultaneously, and then combine to calculate the sum 需要注意的是,将数组划分为多个线程的多个部分,以同时计算这些部分,然后合并以计算总和

All of these are restricted to inside the method code. 所有这些都限于方法代码内部。 The problem is when I write: 问题是当我写:

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

The local anonymous class can only access final or effectively final local variable of the main method, which means I can't create a local variable and then change it to update the result. 本地匿名类只能访问main方法的最终或有效的最终局部变量,这意味着我无法创建局部变量,然后更改它以更新结果。 I can't think of a way to pass a thread's result back to combine with the results from the other threads. 我想不出一种方法来将线程的结果传递回去与其他线程的结果合并。

Is there any way to solve this? 有什么办法解决这个问题?

You can divide up the work in your main thread and do something like this: 您可以在主线程中划分工作,然后执行以下操作:

 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;
         }
     }
 }

And call from another thread like so: 并从另一个线程调用,如下所示:

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();
}

Or, you can use an Executor and a Callable : 或者,您可以使用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