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();
}
}
[/code]
The results of running the above code are as follows:
Copy the code code as follows:
MyThread1
MyThread2