Wednesday, 30 September 2015

Java Thread :Implementing Runnable Interface

package com.JavaInterview.Programs;

/**
 * *A Thread can be created by extending Thread class also. But Java allows only one class to extend,
 *   it wont allow multiple inheritance. So it is always better to create a thread by implementing 
 *  Runnable interface. Java allows you to implement multiple interfaces at a time.
 * * By implementing Runnable interface, you need to provide implementation for run() method.
 * *To run this implementation class, create a Thread object, pass Runnable implementation class        *   object to its constructor. Call start() method on thread class to start executing run() method.
 * 
 * 
 */
public class RunnableThreadJIP implements Runnable{


    public static int myCount = 0;
    public RunnableThreadJIP(){
         
    }
    public void run() {
        while(RunnableThreadJIP.myCount <= 10){
            try{
                System.out.println("Expl Thread: "+(++RunnableThreadJIP.myCount));
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                System.out.println("Exception in thread: "+ex.getMessage());
            }
        }
    }
}

class MyThread {
    public static void main(String a[]){
        System.out.println("Starting Main Thread...");
        RunnableThreadJIP rt = new RunnableThreadJIP();
        Thread t = new Thread(rt);
        t.start();
        while(RunnableThreadJIP.myCount <= 10){
            try{
                System.out.println("Main Thread: "+(++RunnableThreadJIP.myCount));
                Thread.sleep(100);
            } catch (InterruptedException ex){
                System.out.println("Exception in main thread: "+ex.getMessage());
            }
        }
        System.out.println("End of Main Thread...");
    }
}

Output:
Starting Main Thread...
Main Thread: 1
Expl Thread: 2
Main Thread: 3
Expl Thread: 4
Main Thread: 5
Expl Thread: 6
Main Thread: 7
Expl Thread: 8
Main Thread: 9
Expl Thread: 10
Main Thread: 11
End of Main Thread...


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...