Blog

How To Create a Thread in Java ?

Published on

There are two ways to define a thread in Java.

1: By extending Thread class

2: By Implementing Runnable Interface


By Extending Thread Class

Thread class used to create a thread which provides  constructors and methods for creating and operating. 

The thread class extends the object class and implements a runnable interface. The thread class considered the main class which is responsible for implementing multithreading  concept in java or we can say on which Java’s multithreading system is based.

				
					public class Test {

	public static void main(String[] args) {

		MyThread t1 = new MyThread();
		t1.start();
		for (int i = 1; i <= 5; i++) {

			System.out.println("Main Thread");
		}
		
	}

}
class MyThread extends Thread {
	
	public void run() {
	
		for (int i = 1; i <= 5; i++) {

			System.out.println("Child Thread");
		}
	}
}

				
			
				
					Output
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
				
			

Here, we can expect the same output due thread class implementation.

By Implementing Runnable Interface

				
					public class RunnableTest {

	public static void main(String[] args) {

		MyRunnable runnable = new MyRunnable();

		Thread t = new Thread(runnable);
		t.start();

		for (int i = 1; i <= 5; i++) {

			System.out.println("Main Thread");
		}

	}

}

class MyRunnable implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for (int i = 1; i <= 5; i++) {

			System.out.println("Child Thread");
		}

	}

}

				
			
				
					Output:
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Child Thread

				
			

Which approach is best to define a thread?

Among two ways of difining a thread, implements Runnable approach is recommended.

In the first approach our class always extends Thread class, there is no chance of extending any other class. Hence, we are missing inheritece benefits . But, in the second approach while implementing Runnable interface, we can extend any oher class. Hence, wouldn’t miss any inheritence benefit.

Beccause of above reason, implementing Runnable interface approach is recommanded than extending Thread class.

Constructor in Thread class.

1: Thread t=new Thread();

2: Thread t=new Thread(Runnable r);

3: Thread t=new Thread(String name);

4: Thread t=new Thread(Runnable r, String name);

5:  Thread t=new Thread(ThreadGroup group,Runnable target,String name);

6: Thread(ThreadGroup group,String name);

7: Thread(ThreadGroup group, Runnable r,String name);

8:  Thread t=new Thread(ThreadGroup group,Runnable target,String name,long stackSize);

Popular Posts

Copyright © 2024 javadsa.com