I have two threads- A and B. Now requirement is to implement the following things in a Java program:
Functionality:
1) A thread will print i=1 to 50 on doubling i in each step,
2) B thread will print j=200 to 0 on dividing j by 5 in each step
and
Procedure/Mechanism:
1) A will do one step and wait for B,
2) B will do one step and wait for A
and this continues till the conditions match. Here is my code.
Code:
public class JavaApplication6 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
A a = new A();
B b = new B();
a.setOtherThread(b);
b.setOtherThread(a);
a.start();
}
}
class A extends Thread{
Thread b;
public void setOtherThread(Thread t){
b = t;
}
public void run(){
int i =1;
synchronized(b){
while(i<50){
try {
System.out.println("Request i = "+i);
i = i*2;
if(!b.isAlive()){
b.start();
}else{
notify();
}
b.wait();
} catch (InterruptedException ex) {
System.out.println("Error in Request Thread on wait");
Logger.getLogger(JavaApplication6.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("A Thread Will Close Now");
}
}
}
class B extends Thread{
Thread a;
public void setOtherThread(Thread t){
a = t;
}
public void run(){
int j = 200;
synchronized(a){
while(j>5){
try {
System.out.println("J in Response thread = "+j);
j = j/5;
notify();
a.wait();
} catch (InterruptedException ex) {
Logger.getLogger(ReceiveResponse.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("B Will Close Now");
}
}
}
Now it throws exception after A runs for step 2 of its loop after B ran for step 1 in its loop. Output is as follows:
Output:
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at javaapplication6.B.run
Exception in thread "Thread-0" java.lang.IllegalThreadStateException
at java.lang.Thread.start
at javaapplication6.A.run
I am very weak in threading. So it would be very helpful if I could get all the points about my mistakes and the correct ways to achieve my requirements in detail.
Thanks in advance.