Q:

Java program to create a group of a thread

belongs to collection: Java Threading Programs

0

Java program to create a group of a thread

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create a thread group using ThreadGroup class and add child threads to the group, and executed them.

Program/Source Code:

The source code to create a group of a thread is given below. The given program is compiled and executed successfully.

// Java program to create a group of a thread

class MyThread extends Thread {
  MyThread(String threadname, ThreadGroup tg) {
    super(tg, threadname);
    start();
  }
  public void run() {
    System.out.println(Thread.currentThread().getName() + " is running");
  }
}

public class Main {
  public static void main(String[] args) {
    try {
      ThreadGroup group = new ThreadGroup("Parent thread");

      MyThread t1 = new MyThread("Child Thread1", group);
      MyThread t2 = new MyThread("Child Thread2", group);
      MyThread t3 = new MyThread("Child Thread3", group);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Output:

Child Thread1 is running
Child Thread3 is running
Child Thread2 is running

Explanation:

In the above program, we created two classes MyThread and Main. We created MyThread class by extending the Thread class.

The Main class contains a main() method. The main() method is the entry point for the program. Here, we created an object of ThreadGroup class and added the child thread into the thread group and executed them.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to count active threads of a thread g... >>
<< Java program to interrupt the execution of a threa...