In this post, we will see about Runnable interface. Let’s see some basics and then we will see how to create a thread using the Runnable interface.
- The Runnable interface is available in the lang package which has two subinterfaces RunnableFuture and RunnableScheduledFuture(i.e RunnableFuture and RunnableScheduledFuture interface extends Runnable interface).
- The Runnable interface contains run() method, so any class which is going to implements Runnable interface must override run() method.
- The Runnable interface has been marked as a functional interface.
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
- Below are the known classes AsyncBoxView.ChildState, ForkJoinWorkerThread, FutureTask, RenderableImageProducer, SwingWorker, Thread, TimerTask which implements Runnable interface.
Creating a thread using Runnable interface –
package runnableexample;
public class Example1 implements Runnable{
@Override
public void run() {
System.out.println("Thread created using runnable interface");
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
Example1 threadExample = new Example1();
Thread thread = new Thread(threadExample);
thread.start();
}
}
The output is –
