与多线程java的并行求和

时间:2016-12-06 18:03:07

标签: java multithreading

我需要通过并行计算这个等式D =(a-b)+(c-d)来解释连接函数。 假设我有一个等式D =(a-b)+(c-d)。我如何并行使用三个线程来计算(a-b),一个计算(c-d)和显示结果的主线程。我需要表明主要没有在两个线程死之前显示结果。

3 个答案:

答案 0 :(得分:1)

我正在创建他们瘫痪的两个主题:

他们 t1 t2 ;

  • 这里t1计算(a-b)
  • t2正在计算(c-d)

这里main()计算总和:

此代码可以帮助您:

class SumThread extends Thread implements Runnable {
 public SumThread(int a, int b) {
      this.a = a;
      this.b = b;
      sum = 0;
          }

 public void run( ) {
     sum=(a-b);
            } 

 public int getSum( ) {
    return sum;
          }

 private int a, b, sum;

}


public class Sum2 {
  public static void main(String args[]) {
    SumThread t1 = new SumThread(1, 2);
    SumThread t2 = new SumThread(3, 4);
    t1.start( );
    t2.start( );

try {
  t1.join( );
  t2.join( );
} catch(InterruptedException e) {
  System.out.println("Interrupted");
}

System.out.printf("The sum %d \n", t1.getSum( )+t2.getSum());
 }
  }

答案 1 :(得分:1)

正如Javadoc所说,join()等待一个给定的线程死掉 - 因此,它是一个阻塞直到线程完成计算的语句。使用等式:

// Choose a, b, c, and d.
int a = 0;
int b = 1;
int c = 2;
int d = 3;

// Set up an array for the intermediate results.
int[] results = new int[2];

// Create two threads writing the intermediate results.
Thread t0 = new Thread(() -> results[0] = a - b);
Thread t1 = new Thread(() -> results[1] = c - d);

// Start both threads.
t0.start();
t1.start();

// Let the main thread wait until both threads are dead.
try {
    t0.join();
    t1.join();
} catch (InterruptedException e) { /* NOP */ }

// Sum up the intermediate results and print it.
System.out.println(results[0] + results[1]);

使用简单的数组从线程中检索结果有点可疑(请查看this question)。但是,对于这个例子来说已经足够了。

答案 2 :(得分:0)

实际上,您可以不使用线程池(ExecutorService)加入:

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;

public class Main {
    static int calc(int a, int b, int c, int d) throws ExecutionException, InterruptedException {
        var executor = ForkJoinPool.commonPool();
        var f1 = executor.submit(() -> a - b);
        var f2 = executor.submit(() -> c - d);
        return f1.get() + f2.get();
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        System.out.println(calc(1, 2, 3, 4));
    }
}

...或使用与join框架不同类型的CompletableFuture(也将在公共池上运行):

import java.util.concurrent.CompletableFuture;

public class Main {

    static int calc(int a, int b, int c, int d) {
        var s1 = CompletableFuture.supplyAsync(() -> a - b).join();
        var s2 = CompletableFuture.supplyAsync(() -> a - b).join();
        return s1 + s2;
    }

    public static void main(String[] args) {
        System.out.println(calc(1, 2, 3, 4));
    }
}