Main Thread and Child Thread


 

Main Thread and Child Thread

In this segment of tutorial we will learn about the Main Thread and Child Thread.Then We will create an example for Main thread and Child Thread

In this segment of tutorial we will learn about the Main Thread and Child Thread.Then We will create an example for Main thread and Child Thread

  • There are two types of threads in Java Progarm
    • In Java there are Main and Child Threads used in Programming.
  • Main thread is automatically created when program runs.
  • Child Thread gets created by the main thread .


Java Main Thread Example

public class mainchild implements Runnable {
	Thread t1;

	public mainchild(String a) {
		t1 = new Thread(this, a);
		t1.start();
	}

	public void run() {
		for (int x = 1; x <= 3; x++) {
			System.out.println(x + "  this thread is "
					+ Thread.currentThread().getName());
		}
	}

	public static void main(String[] args) {
		mainchild mch = new mainchild("Child ");
		for (int x = 1; x <= 3; x++) {
			System.out.println(x + "  this thread is "
					+ Thread.currentThread().getName());
		}
	}
}

Output

1 this thread is main 1 this thread is Child 2 this thread is Child 3 this thread is Child 2 this thread is main 3 this thread is main

Ads