My aim was to creat e a program that performs the following:
o Create two threads
o One thread asks the user to enter groups of 5 numbers
o As soon as 5 numbers has been entered, the other thread computes it sum
o This continues for each group until the end of input is reached
I wrote the following code but itsd just not running, I guess I have not been able to codea good logic for them to synchronise please help!!!
import java.io.BufferedReader; import java.io.InputStreamReader; public class Thrd1 implements Runnable { public static int wakeup() { return 1; } static int Numbers []= new int[5]; int counter=0; public void run() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String temp=null; try { System.out.println("Enter 5 numbers:"); for(int i=0;i<5;i++) { System.out.println("Enter "+(i+1)+" numner:"); temp=br.readLine(); Numbers[i]=Integer.parseInt(temp); } wakeup(); } catch(Exception e) { System.out.println("Error:"+e.getMessage()); } } } public class Thrd2 implements Runnable { public static int wakeup() { return 1; } public void run() { int sum=0; System.out.println("The sum of numbers is:"); for (int i=0;i<5;i++) { sum+=Thrd1.Numbers[i]; } System.out.println("Sum is ="+sum); wakeup(); } } public class MainClass { public static void main(String[] args) { while (true) { Thrd1 obj1 = new Thrd1(); Thread firstthread = new Thread(obj1, "1st Thread"); Thrd2 obj2 = new Thrd2(); Thread secondthread = new Thread(obj2, "2nd Thread"); if (Thrd1.wakeup()==1) { try { firstthread.wait(); secondthread.start(); } catch (InterruptedException e) { e.printStackTrace(); } } if (Thrd2.wakeup()==1) { try { firstthread.start(); secondthread.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }