Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Wednesday, April 9, 2025

Inter-thread communication, daemon threads, thread groups.

Inter-thread communication:



Program:


 class MyData {

    void produce() throws Exception {

        synchronized(this) {

            System.out.println("Produce method");

            wait(); // waits for notify

            System.out.println("Back to produce");

        }

    }


    void consume() throws Exception {

        synchronized(this) {

            System.out.println("Consume method");

            notify(); // wakes up produce

        }

    }

}


public class InterThreadDemo {

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

        MyData d = new MyData();


        Thread t1 = new Thread

(

new Runnable() {

            public void run() {

                try {

                    d.produce();

                } 

catch (Exception e) 

{

e.printStackTrace();

}

}

}

);


        Thread t2 = new Thread(new Runnable() {

            public void run() {

                try {

                    Thread.sleep(1000); // small delay so that t1 runs first

                    d.consume();

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        });


        t1.start();

        t2.start();

    }

}




Daemon threads: A daemon thread is a low-priority thread that runs in the background to perform tasks without blocking the program from exiting.  It is terminated automatically when all user (non-daemon) threads have finished execution.

In computer science, especially in the context of multithreading in programming (like Java or Python), a daemon thread (also spelled "background thread") is a special kind of thread that runs in the background to perform tasks such as housekeeping, maintenance, or support for user threads.


🔍 Definition

A daemon thread is a low-priority thread that runs in the background to perform tasks without blocking the program from exiting. It is terminated automatically when all user (non-daemon) threads have finished execution.


🧠 Conceptual Explanation

Imagine you are working in a library:

  • You (the user thread) are reading a book.

  • A cleaner (the daemon thread) is working quietly in the background, cleaning shelves.

  • Once you leave the library, the cleaner also stops working, whether the task is completed or not.

Similarly, in a program, when all non-daemon threads finish, the JVM or Python interpreter will not wait for daemon threads to complete and will exit the application, stopping daemon threads as well.


Key Characteristics of Daemon Threads

PropertyDaemon Thread
Runs in backgroundYes
PriorityLower than user threads
LifecycleEnds when all user threads finish
Use caseBackground services (logging, garbage collection, etc.)
StartsMust be set as daemon before starting

⚙️ Use Cases

  • Garbage collectors (in Java Virtual Machine)

  • Scheduler threads (periodic monitoring or cleanup)

  • Auto-saving in IDEs

  • Background loggers

  • Asynchronous data processing



Program:

class MyDaemon extends Thread {
    public void run() 
{
        while(true) {
            System.out.println("Daemon thread is running...");
            try { Thread.sleep(500); } 
catch(Exception e) {}
        }
    }
}

public class DaemonExample {
    public static void main(String[] args) {
        MyDaemon t = new MyDaemon();
        t.setDaemon(true);  // Must be called before start()
        t.start();

        System.out.println("Main thread ends...");
    }
}







Thread groups: 


public class ThreadGroupExample
 {
    public static void main(String[] args) {
        // Creating a thread group
        ThreadGroup group = new ThreadGroup("MyGroup");

        // Creating threads inside the group
        Thread t1 = new Thread(group, new Runnable() {
            public void run() {
                System.out.println("Thread 1 running");
            }
        });

        Thread t2 = new Thread(group, new Runnable() {
            public void run() {
                System.out.println("Thread 2 running");
            }
        });

        t1.start();
        t2.start();

        System.out.println("Thread Group Name: " + group.getName());
        System.out.println("Active Threads: " + group.activeCount());
    }
}



No comments:

Post a Comment