How to create a thread in java

In java there is two ways by using you can create thread.

1) By making use of java.lang.Thread class.

2) By making use of java.lang.Runnable interface.

In this tutorial you will learn to create the thread by using both the way.

Using java.lang.Thread class

The steps required to create a thread by using java.lang.Thread class.

1) Write a class by making the subclass of java.lang.Thread.

2) There is a run () method in java.lang.Thread class, Override that method.

3) Implement thread task inside a run () method.

4) Create an instance of the class which extending with java.lang.Thread class in main method.

5) Call start () method by using above created instance.


package com.java.connect.thread;

public class MyThread extends Thread {

@Override
public void run() {
System.out.println("Running in thread"); // Task implemention
}

public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}

Above code snap show the creating thread using java.lang.Thread class.

When run the MyThread class runtime environment create a main thread and allocate to execution of main method. Java run time environment is the parent of all thread.

So while running the programme there are two threads one is main thread and second thread is created by you.

Whenever main thread is going away, user defined thread doesn’t go away until all the execution completed.

Using java.lang.Runnable interface

The steps required to create a thread by using java.lang.Runnable interface.

1) Write a class by implementing java.lang.Runnable interface.

2) Implement run method from java.lang.Runnable interface.

3) Keep thread task inside run () method.

4) Create an instance to your class which implements the java.lang.Runnable interface.

5) Create an instance to a java.lang.Thread class by passing the instance of your class to thread class constructor.

6) Call start () method with thread class instance.


package com.java.connect.thread;

public class MyThread2 implements Runnable {

public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("Inside thread");
}
}

public static void main(String[] args) {
MyThread2 t1 = new MyThread2();
Thread t = new Thread(t1);
// Start the thred
t.start();
}
}

There are advantages of thread which has been created by implementing java.lang.Runnable interface over the thread created by java.lang.Thread class.

By using java.lang.Runnable interface you can access thread class feature as well as some other class features also by extending any other class.