Mega Code Archive

 
Categories / Java Book / 007 Thread Conncurrent
 

0380 Implementing Runnable

To implement Runnable, a class need only implement a single method called run( ), which is declared like this: void run(); Inside run( ), you will define the code that constitutes the new thread. run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run() returns. After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. After the new thread is created, it will not start running until you call its start( ) method. start( ) executes a call to run( ). class NewThread implements Runnable { Thread t; NewThread() { t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } public class Main { public static void main(String args[]) { new NewThread(); // create a new thread try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }