Threading Concepts in Java
**Multiprocessing vs Multithreading**
Multiprocessing and multithreading are two approaches to achieve concurrent execution in a program.
| Feature | Multiprocessing | Multithreading |
|---------------|-----------------|----------------|
| Definition | Uses multiple processes, each with its own memory space. | Uses multiple threads within a single
process, sharing the same memory. |
| Execution | Each process runs independently. | Threads run within the same process. |
| Memory Usage | More memory consumption due to separate process memory. | Less memory consumption as
threads share memory. |
| Speed | Suitable for CPU-intensive tasks. | Suitable for I/O-bound tasks. |
| Communication | Processes communicate using Inter-Process Communication (IPC). | Threads communicate easily as
they share the same memory. |
| Overhead | Higher overhead due to process creation. | Lower overhead since threads are lightweight. |
---
**Two Ways of Creating Threads in Java**
1. **Extending the Thread class**
```java
class MyThread extends Thread {
public void run() {
System.out.println("Thread running using Thread class");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
```
2. **Implementing the Runnable interface**
```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running using Runnable interface");
}
}
public class ThreadExample {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
```
**Difference Between the Two Approaches:**
- Extending `Thread` class prevents inheritance of any other class as Java supports single inheritance.
- Implementing `Runnable` allows a class to extend another class as well, making it more flexible.
---
**Thread Lifecycle**
A thread goes through several states in its lifecycle:
1. **New:** Thread is created but not started yet.
2. **Runnable:** Thread is ready to run and waiting for CPU.
3. **Running:** Thread is currently executing.
4. **Blocked:** Thread is waiting for a resource to be released.
5. **Waiting:** Thread is waiting indefinitely for another thread's signal.
6. **Timed Waiting:** Thread waits for a specified amount of time.
7. **Terminated:** Thread has finished execution.
---
**Daemon Thread in Java**
A daemon thread is a low-priority background thread that runs in the background to support user threads. It
automatically terminates when all user threads finish execution.
Example:
```java
class DaemonThread extends Thread {
public void run() {
while (true) {
System.out.println("Daemon thread running");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
}
}
public class DaemonExample {
public static void main(String[] args) {
DaemonThread dt = new DaemonThread();
dt.setDaemon(true);
dt.start();
System.out.println("Main thread ending, daemon thread will stop");
}
}
```