ADVERTISEMENT
ADVERTISEMENT

Java program to demonstrate the Thread.join() method

Java example to demonstrate the Thread.join() method.
Submitted by Nidhi, on April 10, 2022

Problem Solution:

In this program, we will demonstrate the Thread.join() method. The join() method is used to join the start of the execution of a thread to the end of another thread's execution.

Program/Source Code:

The source code to demonstrate the Thread.join() method is given below. The given program is compiled and executed successfully.

// Java program to demonstrate Thread.join() method

class MyThread implements Runnable {
  public void run() {
    try {
      System.out.println(Thread.currentThread().getName() + " is alive: " + Thread.currentThread().isAlive());
    } catch (Exception e) {

    }
  }
}

public class Main {
  public static void main(String[] args) {
    try {
      Thread t = new Thread(new MyThread());

      t.start();

      //Waits for 500ms this thread to die.
      t.join(500);

      System.out.println(t.getName() + " is alive: " + t.isAlive());
    } catch (Exception e) {

    }
  }
}

Output:

Thread-0 is alive: true
Thread-0 is alive: false

Explanation:

In the above program, we created two classes MyThread and Main. We created MyThread class by implementing the Runnable interface.

The Main class contains a main() method. The main() method is the entry point for the program. Here, we created a thread and used the join() method to join the start of the execution of a thread to the end of another thread's execution.

Java Threading Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.