How to create a Java Thread

create-java-thread-feature-image

In the tutorial, JavaSampleApproach will introduce ways to create a Java Thread.

I. Use Runnable interface

Runnable interface has a single method public void run(), that is a place to implement code for executing a Thread.
Use Thread(Runnable target) constructor to create a Java Thread.

package com.javasampleappproach.thread;

public class RunableInterface implements Runnable{

	@Override
	public void run() {
		System.out.println("Hello! Using Runable Interface for creating a Java Thread!");
	}

	public static void main(String[] args) {
		(new Thread(new RunableInterface())).start();
	}
}

II. Extends Thread class

Because Thread class had implemented Runnable interface with empty run method implementation. So subclass Thread is a simple way to create a Java Thread, then we implement code in public void run() method for making behavior of the Thread.

package com.javasampleappproach.thread;

public class SubClassThread extends Thread{
	public void run(){
		System.out.println("Hello! SubClass Thread to create a Java Thread!");
	}
	
	public static void main(String[] args) {
		(new SubClassThread()).start();
	}
}

Note: Because Runnable object can subclass a class other and it separates the Runnable task from Thread object so this is a common approach.

III. SourceCode

HowtoCreateJavaThread



By grokonez | January 9, 2017.

Last updated on September 10, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*