Java — Java.lang.Thread.join() Method | Code Factory

/* Waits for this thread to die. */
public final void join() throws InterruptedException
/* Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances. */
public final void join(long millis) throws InterruptedException
/* Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances. */
public final void join(long millis, int nanos) throws InterruptedException
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadJoin {
public static void main(String... args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join(); // #1
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadJoin {
public static void main(String... args) throws InterruptedException {
MyThread.mt = Thread.currentThread();
MyThread t = new MyThread();
t.start();
// t.join(); // It will create deadlock
for(int i=0; i<5; i++) {
System.out.println("Main Thread");
}
}
}
class MyThread extends Thread {
static Thread mt;
public void run() {
try {
mt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
}
}
}
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadJoin {
public static void main(String... args) throws InterruptedException {
Thread.currentThread().join();
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store