Blogjava
The class implementing the Runnable interface must use the instance of the Thread class to create a Thread. You can create a thread using the Runnable interface in 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 Thread class constructor.
Finally, the Thread is created using 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 result of the above Code is as follows:
MyThread1
MyThread2