0

Simply describe

  public static void main(String[] args ){

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread stopped");
        }
    });

    try {
        t.start();
        t.join();
        System.out.println("task completed");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
   }

t.join() The main thread waits for its subthread t to die. the call stack of t.join() just like

join -> join(0)

public final synchronized void join(long millis) 
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;

if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
}

if (millis == 0) {

    while (isAlive()) {
    wait(0);
    }
} else {
    while (isAlive()) {
    long delay = millis - now;
    if (delay <= 0) {
        break;
    }
    wait(delay);
    now = System.currentTimeMillis() - base;
    }
}
}

The main locked the object t and waited for notification. I have some confusion when and where the notify be called. Does the native function stop0() call it?

rachana
  • 3,344
  • 7
  • 30
  • 49
user2256235
  • 295
  • 4
  • 15

1 Answers1

1

Take a look at this: who and when notify the thread.wait() when thread.join() is called?

After run() finishes, notify() is called by the Thread subsystem.

Community
  • 1
  • 1
MichaelS
  • 5,941
  • 6
  • 31
  • 46