Home Tutorial Java Core Java Thread : setDaemon() method

 
 

Share on Google+Share on Google+
Java Thread : setDaemon() method
Posted on: October 22, 2012 at 12:00 AM
Advertisement
In this section we are going to describe setDaemon() method with example in java thread.

Java Thread : setDaemon() method

In this section we are going to describe setDaemon() method with example in java thread.

Daemon Thread  :

In Java Thread, daemon threads are used to perform services for user threads. You can say it they are like service providers for other threads.
It runs in background and most of time created by JVM, performing background tasks.
For example garbage collector thread, screen updater thread, clock handler thread etc.

public final void setDaemon(boolean on) : This method sets user thread either daemon thread or not by providing value true or false.
It tells the JVM to make the thread a daemon thread.

Example :  In this example we are setting  thread 1 as daemon thread.

public class ThreadSetDaemon implements Runnable {

	public void run() {
		System.out.println("Thread name : " + Thread.currentThread().getName());
	}

	public static void main(String[] args) throws Throwable {

		/* Create a thread as a daemon thread */
		Thread thread1 = new Thread(new ThreadSetDaemon());
		//thread1.setDaemon(true);
		thread1.start();
		System.out.println("Thread is set as daemon thread.");

		Thread thread2 = new Thread(new ThreadSetDaemon());
		thread2.start();

		System.out.println("Active threads = " + Thread.activeCount());

		thread1.join();
		thread2.join();
		System.out.println("Thread name : " + Thread.currentThread().getName());
		
	}
}

Output :

Thread is set as daemon thread.
Active threads = 3
Thread name : Thread-0
Thread name : Thread-1
Thread name : main

Advertisement

Related Tags for Java Thread : setDaemon() method :


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 22, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com