Home > Mobile >  Thread join(1) usage in mutlithread wait-notify example in Java
Thread join(1) usage in mutlithread wait-notify example in Java

Time:11-03

I have example with wait-notify application which is invoked from main:

public class Handler {

public void producer () throws InterruptedException {
    Thread.sleep(1000);
    synchronized(this) {
        System.out.println("Producer started ######...");
        wait();
        System.out.println("Proceed running in current thread after notification and 5s sleep in consumer tread");
    }
}

public void consumer() throws InterruptedException {
    Thread.sleep(2000);
    synchronized(this) {
        System.out.println("Consumer started #####...");
        notify();
        Thread.sleep(5000);
    }

}

}

and invoker

public class ThreadRunner {

public static void main(String[] args) {
    
    Handler handler = new Handler();
    
    Thread thread1 = new Thread(() -> {
        try {
            handler.producer();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    
    Thread thread2 = new Thread(() -> {
        try {
            handler.consumer();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    thread1.start();
    thread2.start();
    
    
    try {
        thread1.join(1);
        thread2.join(1);
    } catch (InterruptedException e) {
    System.out.println("exception");
    }
}

}

As I expected "exception" message should be printed as I join(1) to threads and wait them to die only 1 mills, but they are sleeping more than that. What am I missing?

CodePudding user response:

join(1) has 3 ways 'out':

  • The thread you called join on ends, in which case your call to join(1) stops running by returning.
  • Some code someplace (it's only code that can do it, e.g. a user pressing CTRL C or whatnot never causes this) calls .interrupt() on your thread; join(1) stops running by throwing InterruptedException.
  • 1 milliseconds passes, in which case join(1) stops running by returning.

You are evidently under the impression that the join method exits by way of throwing InterruptedEx if the time runs out. It does not.

  • Related