Home‎ > ‎Applied Core Java‎ > ‎Threads‎ > ‎

Runnable Interface

Problem :  How you will make a class thread that is already child of another class?

Solution : If a class is already child of another class then java.lang.Runnable interface need to be implemented to make it thread. Runnable interface has only one method 'run()'.

Program :

Step 1 - Coding


Create a text file c:\sunilos\HelloWithRunnableThread.java  and copy below contents.

/*
 * A program Implementing runnable.
 */

public class HelloWithRunnableThread extends Object implements Runnable {

    String name = null;

    public HelloWithRunnableThread(String threadName) {

        name = threadName;
    }

    public void run() {
       for (int i = 0; i < 50; i++) {
           System.out.println(i + " Hello Runnable Thread " + name);
       }
    }

}

Step 2 - Creating Test Program


Create a text file c:\sunilos\TestRunnableThread.java  and copy below contents.


/*
 * A program to test runnable implemented thread
 */

public class TestRunnableThread {

    public static void main(String[] args) {
       
        HelloWithRunnableThread mahi  = new HelloWithRunnableThread("Dhoni");
       
        Thread t1 = new Thread(mahi); //Wrap Runnable class into thread
       
        HelloWithRunnableThread yuvi  = new HelloWithRunnableThread("Yuvraj");
       
        Thread t2 = new Thread(yuvi);//Wrap Runnable class into thread
       
        t1.start();
        t2.start();
       
        for (int i = 0; i < 500; i++) {
            System.out.println(i + " This is Main");
        }

    }

}

Step 3 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy HelloWithRunnableThread.java  and  TestRunnableThread.java into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile HelloWithRunnableThread.java and TestRunnableThread.java with help of
    •  javac HelloWithRunnableThread.java command.
    •  javac TestRunnableThread.java command. Compiled class file will be created in  the same folder.
  5. Congratulations!! your Test Java program is ready to serve.

Step 4 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your  java program from command prompt with help of 
    • java TestRunnableThread  command.

Output


0 Hello Runnable Thread Dhoni
0 Hello Runnable Thread Yuvraj
0 This is Main
1 Hello Runnable Thread Dhoni
1 Hello Runnable Thread Yuvraj

....
....

<<Previous | Next>>
ċ
HelloWithRunnableThread.java
(1k)
Mahima Hardia,
Aug 20, 2011, 5:28 AM
ċ
TestRunnableThread.java
(1k)
Mahima Hardia,
Aug 20, 2011, 5:26 AM
Comments