我需要通过并行计算该方程d =(a-b) (c-d)来解释联接函数。假设我有一个方程d =(a-b) (c-d)。如何使用三个线程计算(A-B),计算(C-D)和主线程以显示结果的三个线程进行此方程。我需要证明,在两个线程死亡之前,主不会显示结果。
正如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]);
使用一个简单的数组从线程中检索结果有点腥(查看此问题)。但是,对于此示例就足够了。
我正在创建两个线程,它们瘫痪了:
它们是 t1 和 t2 ;
- 在这里T1计算(A-B)
- T2正在计算(C-D)
在此处计算总和:
此代码可能会帮助您:
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());
}
}
实际上您可以在不使用线程池加入的情况下做(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));
}
}
...或使用CompletableFuture
框架的其他类型的join
(也将在公共池上运行):
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));
}
}