Threads
Create threads
Implementing the Runnable interface
A procedure for creating a thread by implementing the Runnable interface
- Create a class that implements the Runnable interface.
- Implement the run method to perform the desired task.
- Create the thread by supplying an instance of the Runnable class to the Thread constructor.
- Call the start method of the thread object.
A version of the Count Down application that uses the Runnable interface
public class CountDownRunnableApp
{
public static void main(String[] args)
{
Thread count1 = new Thread(new CountDownEven());
Thread count2 = new Thread(new CountDownOdd());
count1.start(); // start the countdown threads
count2.start();
}
}
class CountDownEven implements Runnable // this class counts even numbers
{
public void run()
{
Thread t = Thread.currentThread();
for (int i = 10; i > 0; i-= 2)
{
System.out.println(t.getName() + " Count " + i);
Thread.yield(); // allow the other thread to run
}
}
}
class CountDownOdd implements Runnable // this class counts odd numbers
{
public void run()
{
Thread t = Thread.currentThread();
for (int i = 9; i > 0; i-= 2)
{
System.out.println(t.getName() + " Count " + i);
Thread.yield(); // allow the other thread to run
}
}
}