2016-12-06 94 views
0

我需要通过并行计算这个方程D =(a-b)+(c-d)来解释连接函数。 假设我有一个方程D =(a-b)+(c-d)。我怎么能并行使用三线程计算(a-b),一个计算(c-d)和主线程来显示结果。我需要证明主要是在这两个线程死亡之前不显示结果。用多线程java并行求和

+1

创建子类的三个对象并调用run()方法可能有效@BetterEnglish –

回答

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)。但是,这个例子就足够了。

1

我创建两个线程,他们都瘫痪了:

他们T1T2;

  • 这点t1计算(AB)
  • T2的计算(CD)

这里主要()计算总和:

这段代码可以帮助你:

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