Java Multithreading - using Runnable
Threads can be implemented either extending the class Thread or by implementing the interface Runnable.
Advantages of using Runnable
- In Java, any class can extend only one class. If you implement a Thread by extending class Thread, it becomes impossible to extend any other class. Since Runnable is an interface, any class implementing Runnable interface can extend a class. Hence, using Runnable is often preferred.
Java Example - Thread implementing interface Runnable
public class ThreadUsingRunnableExample implements Runnable{
String threadName;
public ThreadUsingRunnableExample(String name){
this.threadName=name;
}
public void run(){
System.out.println("Inside Runnable thread: " + threadName);
}
public static void main(String a[]){
Thread thread1 = new Thread(new ThreadUsingRunnableExample("Thread1"));
Thread thread2 = new Thread(new ThreadUsingRunnableExample("Thread2"));
Thread thread3 = new Thread(new ThreadUsingRunnableExample("Thread3"));
Thread thread4 = new Thread(new ThreadUsingRunnableExample("Thread4"));
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
Output - Thread implementing interface Runnable
Inside Runnable thread: Thread3 Inside Runnable thread: Thread4 Inside Runnable thread: Thread2 Inside Runnable thread: Thread1