A method for Java threads to create threads using the Runnable interface
- 2020-04-01 01:49:24
- OfStack
A class that implements the Runnable interface must use an instance of the Thread class to create a Thread. Creating a thread through the Runnable interface is divided into two steps:
1. Instantiate the class that implements the Runnable interface.
2. Create a Thread object and pass the first step's instantiated object as a parameter to the constructor of the Thread class.
Finally, a Thread is created through the start method of the Thread class.
The following code demonstrates how to create threads using the Runnable interface:
package mythread;
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
MyRunnable t1 = new MyRunnable();
MyRunnable t2 = new MyRunnable();
Thread thread1 = new Thread(t1, "MyThread1");
Thread thread2 = new Thread(t2);
thread2.setName("MyThread2");
thread1.start();
thread2.start();
}
}
The result of the above code is as follows:
MyThread1
MyThread2