Sunday, 20 November 2016

What is Runnable Interface In Java ?

Previously we have discussed about


Interface Runnable

All Known Subinterfaces:
RunnableFuture<V>, RunnableScheduledFuture<V>

All Known Implementing Classes:
AsyncBoxView.ChildState, ForkJoinWorkerThread, FutureTask, RenderableImageProducer, SwingWorker, Thread, TimerTask

Declaration of Runnable:
public interface Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

This interface is designed to provide a common protocol for objects that wish to execute code while they are active.

A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

Method Summary of Runnable:

Modifier and Method Name
Description
void run()
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

Example of Runnable:

class P implements Runnable {

@Override
public void run() {
for(int i=1;i<=5;i++){
System.out.println("Thread P : "+i);
}
System.out.println(" : End of Thread P : ");
}
}
public class RunnableInterfaceExample {
public static void main(String[] args) {
P p = new P();
Thread t = new Thread(p);
t.start();
System.out.println("END OF MAIN THREAD");
}
}
Program Output:

END OF MAIN THREAD
Thread P : 1
Thread P : 2
Thread P : 3
Thread P : 4
Thread P : 5
 : End of Thread P : 


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment