Thread API And Daemon Thread in JAVA

  • By
  • March 2, 2022
  • JAVA Programming

Thread API and Daemon Thread in JAVA-

Java Thread class methods –

1.void start()    

This method is used to start the processing  of the thread.

2.void run()

This method  is used to execute a   thread object.

3.static void sleep(long miliseconds)

This method  allows you to sleep or block a thread for the specified amount of time.

4.static Thread currentThread()

This method  returns a reference of the thread object that is  currently being executed in our system.

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

5.void join()

In this method, next thread  waits for a previous thread to die. As first thread gets die, it starts execution of itself

 

//program to show the use of join() method of Thread class

 

package Multi;

class Aaa implements Runnable

{

  public void run()

  {

   for(int i=0;i<5;i++)

  {

System.out.println(i);

try { Thread.sleep(1000); }   catch(Exception e) {}

      }

 

  }

}

 

public class JoinDemo {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

 

Aaa o1= new Aaa();

        Thread t1=new Thread(o1); 

        Thread t2=new Thread(o1); // OR Thread t1= new Thread(new A());

        Thread t3 = new Thread(o1);

        

 System.out.println(“thread A:”);

         

       t1.start();

        

       try {  t1.join();} catch(Exception e) {}

       

      System.out.println(“T1 thread execution completed”);

         

t2.start();

    try {  t2.join();} catch(Exception e) {}

    System.out.println(“T2 thread execution completed”);

  

    t3.start();

}

}

/*

output:

thread A:

0

1

2

3

4

T1 thread execution completed

0

1

2

3

4

T2 thread execution completed

0

1

2

3

4    */

6.public final int getPriority()  

This method  returns the priority of the currently executing  thread.

7.public final void setPriority(int a)

This method  is used  to sets/updates  the priority of the thread.

Thread class provides 3 constant properties:

i.public static int MIN_PRIORITY:   It is the min priority of a thread. The value of it is 1.

ii.public static int NORM_PRIORITY:   It is the normal priority of a thread. The value of it is 5.

iii.public static int MAX_PRIORITY:    It is the max priority of a thread. The value of it is 10.

8.public final String getName()

It returns the name of the currently executing thread.

9.public final void setName(String a) 

It sets/updates the name of the thread.  

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

10.public long getId()

It returns the id of the thread. The thread ID is a positive number which was generated at the time of thread creation. Thread id is unique for every thread object. The thread ID is not during its lifetime. When the thread is terminated, the ID of the thread can be reused.

//Program for showing the use of methods like currentThread(), getName(), setPriority(),  getPriority(),getId(), getState()

package Multi;

class A20 extends Thread

{

public void run()

{

System.out.println(“currently executing thread name : “+currentThread().getName());

}

}

public class ThreadMethodDEmo {

 

public static void main(String[] args) {

A20 t1=new A20();   

A20 t2= new A20();

        t1.start();    //thread scheduler

 

        t2.start();

 

t1.setPriority(9);                               

System.out.println(“Thread  priority is = “+t1.getPriority());

t1.setName(“My thread”);

System.out.println(“thread name is  = “+t1.getName());

System.out.println(“thread id is = “+t1.getId());

System.out.println(“thread state is = “+t1.getState());

}

 

}

11.public final boolean isAlive()

This method tests whether the thread is alive or not. It returns true if the thread is alive, else it returns false.

//program to show the use of isAlive() method

package Multi;

class A22 extends Thread

{

public void run()

{

System.out.println(“currently executing thread name : “+currentThread().getName());

}

}

public class ISaliveMethod {

public static void main(String[] args) {

A22 t1=new A22();   //9  5ms

System.out.println(“Before starting Thread isAlive  = “+t1.isAlive());

 

t1.start();

System.out.println(“After starting Thread isAlive  = “+t1.isAlive());

}

}

 

/*

 

Before starting Thread isAlive  = false

After starting Thread isAlive  = true

currently executing thread name : Thread-0   */

12.public static void yield(    ) 

The yield() method of thread class causes the currently executing thread  to temporarily pause and allow other threads to execute. As the execution of a previously executed thread gets completed, the current thread resumes its execution.

 

//program to show the use of yield() method of Thread class

 

package Multi;

 

class Th1 extends Thread

{

public void  run()

{

for(int i=0;i<5;++i)

{

yield();

System.out.println(“Thread started : “+Thread.currentThread().getName());

  }

System.out.println(“Thread ended : “+Thread.currentThread().getName());

}

}

public class YieldDemo {

 

public static void main(String[] args) {

 

  Th1 t1= new Th1();

   

  t1.start();

  for(int i=0;i<5;++i)

{

System.out.println(“Thread started : ” +Thread.currentThread().getName());

  Thread.yield();

   

System.out.println(“Thread ended : “+Thread.currentThread().getName());

   

}

 

}

/*

output:

Thread started : main

Thread started : Thread-0

Thread started : main

Thread started : Thread-0

Thread started : main

Thread started : Thread-0

Thread started : main

Thread started : Thread-0

Thread started : main

Thread started : Thread-0

Thread ended : Thread-0

Thread ended : main    */

 

//void suspend(), void resume() , void stop(),public void destroy(). These 4 methods are deprecated from java.

13.public void suspend()

This method is used to suspend the currently executing  thread. Means, it puts the thread from running to waiting state.

14.public void resume()

This method is used to resume the suspended thread.

15.public  void stop()

This method is used to stop the currently executing thread. 

Once we stop the thread by calling stop() method, we aren’t able to restart it again.  

16.public void destroy()

This method is used to destroy the thread group and all of its subgroups.

 17. boolean isDaemon()

 

This method tests if the thread is a daemon thread. It returns true if the currently executing thread is a daemon thread.

18.void setDaemon(boolean b)

This method makes the thread as a daemon or user thread. If we  pass true as a parameter to a daemon thread then it sets the current thread as a daemon thread.

19.Thread.State getState()     

This method is used to return the state of the currently executing  thread.

20.String toString()

This method is used to return a string representation of this thread, including the thread’s name, priority, and thread group.

21.void notify()

This method is used to give the notification for only one thread which is waiting for a particular object.

22.void notifyAll()

This method is used to give the notification to all waiting threads of a particular object.

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

DAEMON THREAD in Java and user  thread –

Daemon thread is a type of thread that runs in the background to perform tasks such as garbage collection.

Garbage collection is the process of destroying the unused or unreferenced objects from the memory.  gc, finalizer are the examples of a daemon thread.

Daemon thread is a low priority thread in java that provides services to the user thread.

Means it is a service provider type of thread. Its life depends on the user threads means when the user thread gets terminated this daemon thread will get destroyed automatically from the memory by the JVM. 

This thread  has no role in the program execution  than to serve the user threads.

When a new thread is created in the memory it inherits the daemon properties of its parent. That’s why  all threads created in the  main method (child threads of main thread) are non-daemon by default, because the main thread is not a  daemon. 

However you can make a user thread to Daemon by using setDaemon() method of thread class.

 

//program that create daemon thread and show the use of isDaemon() and setDaemon() method

 

package Multi;

 

class Daemon5 extends Thread

{

public void run()

{

if (Thread.currentThread().isDaemon())       //check whether the //currently running thread is daemon thread or not

  {

              System.out.println(“Daemon thread is working…”);

        }

        else

        {

      System.out.println(“user thread working”);

    }

    }

}

 

public class DaemonTh {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

 

Daemon5 t1 = new Daemon5();

Daemon5 t2 = new Daemon5();

Daemon5 t3 = new Daemon5();

t1.setDaemon(true);        //set the currently running user thread to daemon //thread

t1.start();

t2.start(); 

t2.setPriority(6);;

t3.setDaemon(true);

t3.start();

}

 

}

/*

output:

 

user thread working

Daemon thread is working…

user thread working */

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

User Threads are having high priority as compared to daemon threads. The JVM will wait for the  thread to complete its task, before terminating it. But JVM does not wait for daemon threads. It directly terminates the daemon thread as soon as user thread complete its task

Author:-

Pooja Nandode-Bhavsar

SevenMentor Pvt Ltd

Call the Trainer and Book your free demo Class for now!!!
call icon

© Copyright 202! | Sevenmentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*