Digital Marriage Invitation Card

How to Create Thread in Java


This tutorial will explain how to create a Thread in Java. 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 operation 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();
	}

}

Share this article on: