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();
}
}
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
Property | Daemon Thread |
---|---|
Runs in background | Yes |
Priority | Lower than user threads |
Lifecycle | Ends when all user threads finish |
Use case | Background services (logging, garbage collection, etc.) |
Starts | Must 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
No comments:
Post a Comment