Classes that implement 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 object instantiated in the first step as a parameter to the constructor of the Thread class.
Finally, create the thread through the start method of the Thread class.
The following code demonstrates how to use the Runnable interface to create a thread:
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 running results of the above code are as follows:
MyThread1 MyThread2