Daemon Thread in Java
Java Programming

Daemon Thread in Java

 

Daemon Thread

There are two types of threads

  • User Threads
  • Daemon Threads

The threads created by the user(create a thread in the program ) are called user threads.

The threads that work in the background providing service to others are called Daemon Threads.

The two methods used only  in the daemon thread, not in the user thread are:

  • Public void setDaemon(Boolean value): sets a thread to be a daemon thread.
  • Public Boolean isDaemon(): checks if the given thread is a daemon.

Example of Daemon Thread in Java….

class threadtest implements Runnable

{

Thread t1,t2;

public threadtest()

{

t1=new Thread(this);

t1.start();

t2=new Thread(this);

t2.setDaemon(true);

}

public void run()

{

System.out.println(Thread.activeCount());

System.out.println(t1.isDaemon());

System.out.println(t2.isDaemon());

}

public static void main(String ass[])

{

new threadtest();

}

}

Daemon Thread in Java

Explanation…

We create two threads t1 and t2.

Set the t2 thread to be a daemon thread by using the setDaemon() method.

Daemon() is used to find whether the process of converting the user-defined thread has been successful or not (it’s working or not). This method returns true if the thread is a daemon if the thread is not a daemon then it gives false.

This program also prints the total number of threads that are running in a program (using activeCount()).

Recommended Posts

C++ Programming

Visibility modes in C++

In C++, visibility modes refer to the accessibility of class members (such as variables and functions) from different parts of a program. C++ provides three visibility modes: public, private, and protected. These modes control the access levels of class members concerning the outside world and derived classes. Public: Members declared as public are accessible from […]

Rekha Setia 
C++ Programming

Inheritance in C++

In C++, inheritance is a fundamental concept of object-oriented programming (OOP) that allows you to create a new class based on an existing class, known as the base or parent class. The new class is called the derived or child class. Inheritance facilitates code reuse and supports the creation of a hierarchy of classes. There […]

Rekha Setia 
C++ Programming

C++ Classes and Objects

In C++, classes and objects are fundamental concepts that support object-oriented programming (OOP). Here’s a brief overview of classes and objects in C++: Classes: In C++, a class is a user-defined data type that allows you to encapsulate data members and member functions into a single unit. Classes are the building blocks of object-oriented programming […]

Rekha Setia 

Leave A Comment