2016-12-06 7 views
0

この式D =(a-b)+(c-d)を並列に計算して結合関数を説明する必要があります。 私は方程式D =(a-b)+(c-d)を仮定する。どのようにして(a-b)を計算するために3つのスレッドを使用し、(c-d)を計算するために3つのスレッドを使用し、結果を表示するためにメインスレッドを使用して、私はメインがその2つのスレッドが死んでしまう前に結果を表示していないことを示す必要があります。私は、彼らが麻痺している2つのスレッド作成していマルチスレッドJavaとの並列和

+1

サブクラスの3つのオブジェクトを作成して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です。ここで

  • t2は、総合計を計算)(メインここで(CD)

を計算している(AB)を計算t1の:

このコードはあなたを助けることがあります。

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()); 
} 
    } 
関連する問題