How to Create Thread in Java


This tutorial will explain how to create a Thread in Java. A thread can be created by two way in Java…

  1. By extending Thread Class
  2. By implementing Runnable Interface

But before start creating Thread, it is necessary to know about Thread.

What is Thread in Java

Threads are lightweight processes. In the Java programming language, concurrent programming is mostly concerned with threads. By using Thread, you can perform multiple operations in your application like playing audio, printing document, coding, etc.

Example of Extending Thread Class

ExtndThreadClass.java

package org.websparrow.thread;

public class ExtndThreadClass extends Thread {

	@Override
	public void run() {
		System.out.println("Hello, I am extended thread class.");

	}

	public static void main(String[] args) {
		ExtndThreadClass t = new ExtndThreadClass();
		t.start();
		// (new ExtndThreadClass()).start();
	}

}

Example of Implementing Runnable Interface

ImplmntRunnableIntrface.java

package org.websparrow.thread;

public class ImplmntRunnableIntrface implements Runnable {

	@Override
	public void run() {
		System.out.println("Hello, I am Implemented thread.");
	}

	public static void main(String[] args) {
		ImplmntRunnableIntrface i = new ImplmntRunnableIntrface();
		Thread t = new Thread(i);
		t.start();
		// (new Thread(new ImplmntRunnableIntrface())).start();
	}

}

About the Author

Atul Rai
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.