0

I have two Java classes

public class Firstclass
{
    public static void main(String args[]) throws InterruptedException
    {
        System.out.println("Main start....");
        Secondclass s=new Secondclass();

        Thread t1 = new Thread(s);
        t1.setName("First Thread");

        Thread t2=new Thread(s);
        t2.setName("Second Thread");

        t1.start();

        t2.start();
        System.out.println("Main close...");           
    }
}

and

public class Secondclass implements Runnable
{ 
    public static Object obj;

    int counter=10;

    public  void inc()
    {
        counter++;
    }

    public  void dec()
    {
        counter--;
    }

    @Override
    public void run()
    {
        try
        {
            loop();
        }
        catch(Exception e)
        {
            System.out.println("exception is"+e);
        }
    }

    public void loop() throws InterruptedException
    {
        for(int i=0;i<10;i++)
        {            
            if(Thread.currentThread().getName().equals("First Thread"))
            {
                Thread.currentThread().wait();
                inc();                
            }
            else
            {
                dec();
            }
            System.out.println("Counter=="+counter);
        }
    } 
}

My first question is: I want my first thread to wait until second thread completes and I am able to acheive that but in the output I am getting the exception java.lang.IllegalMonitorStateException.I don't know why.

My second question is: Can you please guide me any tutorial site where I can learn wait(), notify and notifyall() methods from basics.

Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74
TruePS
  • 493
  • 2
  • 12
  • 33

2 Answers2

2

Answer 1:- you need to use join() as below :-

t2.start();
t2.join();

t1.start();
t1.join();

Answer 2:- refer this link for wait and notify example.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Anchit Pancholi
  • 1,174
  • 4
  • 14
  • 40
2

I want my first thread to wait until second thread completes and I am able to acheive that but in the output I am getting the exception 'java.lang.IllegalMonitorStateException'.I don't know why.

The wait() method is declared in the Object class, the granddaddy of all reference types in Java. As such, you can invoke the method on any expression that results in an object reference.

The javadoc says the following

Causes the current thread to wait until another thread invokes the java.lang.Object.notify() method or the java.lang.Object.notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

So if you're calling it with

Thread.currentThread().wait();

but you've never synchronized (ie. got the monitor) on the object returned by

Thread.currentThread()

then you will get that IllegalMonitorException.

As a side note, don't every synchronize on Thread instances. They have some unexpected behavior notifying themselves at the end of their life cycle.

One possible solution to your problem is to provide a shared Object to both your Runnable instances. Each one attempts to synchronize on that object around some block of code. The other thread will have to wait until the one that first acquired the monitor finishes using it.

However, don't rely on order here. The Thread scheduler will decide when each threads runs.

Can you plz guide me any tutorial site where I can learn wait(),notify and notifyall() methods from basics.

Any time you have a question like this, just google java <the thing you want>. In this case, you need to review the Javadoc and the Concurrency tutorials.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724