Home Tutorial Java Core Java : Runnable Thread

 
 

Java : Runnable Thread
Posted on: October 16, 2012 at 12:00 AM
In this tutorial we are describing Runnable Thread with example.

Java : Runnable Thread

In this tutorial we are describing Runnable Thread with example.

Runnable Thread :

Runnable thread is an easy way to create a thread by implementing the Runnable interface. You need to implement a single method called run().
Its syntax like following -

public void run( )

Now you can put your code inside the run() method. run() can call another methods too. After creating class that implements Runnable interface, you can create object of type Thread under that class.
There are many constructor defined by the Thread like -
Thread(), Thread(String threadName), Thread(Runnable threadOb, String threadName) etc..
After creating new Thread, call start() method which is declared in thread.

Example :  In this example we are creating thread by using Runnable interface.

class RunnableThread implements Runnable {

	Thread thread;

	public RunnableThread() {
	}

	public RunnableThread(String threadName) {
		/* Creating new thread */
		thread = new Thread(this, threadName);
		System.out.println(thread.getName());
		/* Starting thread */
		thread.start();
	}

	public void run() {
		/* Display info about current thread */
		System.out.println(Thread.currentThread());
	}
}

public class RunnableThreadExample {

	public static void main(String[] args) {
		Thread th1 = new Thread(new RunnableThread(), "thread1");
		Thread th2 = new Thread(new RunnableThread(), "thread2");
		RunnableThread th3 = new RunnableThread("thread3");
		/* Threads start */
		th1.start();
		th2.start();

		try {
			Thread.currentThread();
			/* delay for a second */
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
		/* Display info about current thread */
		System.out.println(Thread.currentThread());
	}
}

Output :

thread3
Thread[thread3,5,main]
Thread[thread2,5,main]
Thread[thread1,5,main]
Thread[main,5,main]

Related Tags for Java : Runnable Thread :


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.