0

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.

fs71gh
  • 63
  • 2
  • 7
  • 1
    Why do you want to do this in 2 threads? Do A, then do B, then repeat - works much more straightforwardly in a single thread. – Andy Turner Apr 26 '16 at 15:36
  • Why wouldn't you post the exception stack trace in your question? Why do you invoke `wait` on `a`, but invoke `notify` on `this`? – Savior Apr 26 '16 at 15:37
  • Why do you use `synchronized` immediately inside the `run()` method of both? That immediately locks both threads with no escape. – Stewart Apr 26 '16 at 15:37
  • (But if I had to do this in multiple threads, I'd use a [`SynchronousQueue`](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/SynchronousQueue.html)) – Andy Turner Apr 26 '16 at 15:39
  • I already have told that my knowledge in threading is not good. It should already have answered all of your questions. – fs71gh Apr 26 '16 at 15:42
  • 1
    We are not here to teach you threading. You wrote some code, you now have to explain why you wrote it this way. This way we can understand your misunderstanding. That's what we expect when we say _show effort_. – Savior Apr 26 '16 at 15:42
  • @AndyTurner Actually I need to apply this idea in a program where I must use thread. This was to get myself preped for that :) – fs71gh Apr 26 '16 at 15:43
  • 1
    The post I picked to close this as a duplicate of operates on the same principle as what you want, check out the examples, they should be helpful. Also make sure you read the post http://stackoverflow.com/questions/886722/how-to-use-wait-and-notify-in-java Do not lock on thread objects. – Nathan Hughes Apr 26 '16 at 15:49

0 Answers0