Krivalar Tutorials 
Krivalar Tutorials

Java Multithreading - using Runnable






Threads can be implemented either extending the class Thread or by implementing the interface Runnable.

Advantages of using Runnable

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