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

标签 java java-threads

我必须创建一个方法来计算数组中所有元素的总和。需要注意的是,数组被分成多个部分,供多个线程同时计算这些部分,然后组合起来计算总和

所有这些都仅限于方法代码内部。问题是当我写:

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

本地匿名类只能访问 main 方法的 Final 或有效 Final 局部变量,这意味着我无法创建局部变量然后更改它以更新结果。我想不出一种方法将线程的结果传回以与其他线程的结果相结合。

有什么办法可以解决这个问题吗?

最佳答案

您可以在主线程中划分工作并执行以下操作:

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

或者,您可以使用 Executor和一个Callable :

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

关于Java:线程之间的通信仅限于一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48919408/

相关文章:

java - Eclipse Mars 在 Java 8 Update 71 后无法启动

linux - 允许运行的最大线程数

Javafx 在哪里将标签绑定(bind)到 StringProperty

java - TransformClassesWithNewClassShrinkerForDebug 错误

java - 在jar文件之外创建并读取xml文件

java - 如何将 AAR 转换为 JAR

JavaFX - 如何在退出应用程序之前关闭所有正在运行的线程?

java - 使用线程按固定时间间隔调用函数

java - Java中如何通知特定的线程

java.io.StreamCorruptedException : invalid stream header: EFBFBDEF