Home Tutorial Java Core Java : Runnable Thread

 
 

Share on Google+Share on Google+
Java : Runnable Thread
Posted on: October 16, 2012 at 12:00 AM
Advertisement
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]

Advertisement

Related Tags for Java : Runnable Thread :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 16, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com