### 1.
**Thread Creation in Java**
In Java, a thread can be created using two main approaches:
- **Extending the `Thread` class**:
In this approach, a class extends the `Thread` class and overrides its
`run()` method. This method contains the code that defines the task
performed by the thread. To start the thread, the `start()` method is called,
which internally calls the `run()` method.
```java
Class MyThread extends Thread {
Public void run() {
[Link](“Thread is running”);
Public class Main {
Public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link](); // This starts the new thread
```
- **Implementing the `Runnable` interface**:
Instead of extending `Thread`, the more common way is to implement
the `Runnable` interface. The `Runnable` interface has only one method,
`run()`. After creating a `Runnable` object, it’s passed to the `Thread` class
constructor, and the thread is started using the `start()` method.
```java
Class MyRunnable implements Runnable {
Public void run() {
[Link](“Runnable is running”);
Public class Main {
Public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
[Link](); // This starts the new thread
```
**Key Points**:
- `start()` method creates a new thread and calls the `run()` method.
- Implementing `Runnable` is more flexible because it allows extending
other classes.
### 2. **Thread Life Cycle**
The life cycle of a thread in Java goes through the following states:
- **New**: The thread is created but not yet started. It exists but hasn’t
executed yet.
```java
Thread t = new Thread(); // Thread is in “new” state
```
- **Runnable**: The thread is ready to run and waiting for CPU time to
execute. When the `start()` method is called, the thread moves from the
“new” state to the “runnable” state.
```java
[Link](); // Now the thread is in “runnable” state
```
- **Blocked**: The thread is waiting for a monitor lock to enter a
synchronized block/method.
- **Waiting**: The thread is waiting indefinitely for another thread to
perform a specific action (like notify it). This state is entered using the
`wait()` method.
- **Timed Waiting**: The thread is waiting for a specified period (e.g., using
`sleep()` or `join(long)` methods).
- **Terminated**: The thread has completed execution, either by returning
from the `run()` method or because an exception occurred.
**Diagram**:
```
New → Runnable → Running → Blocked/Waiting/Timed Waiting → Terminated
```
**Explanation**:
Each state represents different moments in a thread’s execution path.
Understanding these states helps in managing concurrency issues.
### 3. **Life Cycle Methods in Java Threads**
Threads in Java have several life cycle methods that control their execution.
The most important methods include:
- **`start()`**: This method is used to start a new thread. It moves the
thread from the “new” state to the “runnable” state.
```java
[Link]();
```
- **`run()`**: This method contains the task the thread will execute. It
should not be called directly (it is called internally when `start()` is invoked).
- **`sleep(long millis)`**: This method pauses the execution of the thread
for a specified time.
```java
[Link](1000); // Pauses for 1 second
```
- **`yield()`**: This method suggests to the thread scheduler that the
current thread is willing to yield its current use of a CPU.
```java
[Link](); // Yields CPU control to other threads
```
- **`join()`**: This method ensures that the calling thread waits for the
thread on which `join()` is called to complete.
```java
[Link](); // The current thread waits for “t” to finish
```
**Key Differences**:
- `start()` creates a new thread, while `run()` just executes in the current
thread.
- `sleep()` pauses a thread for a specific duration, while `join()` waits for
another thread to finish.
### 4. **Synchronization in Java**
In multithreading, synchronization is critical to prevent race conditions,
where multiple threads access shared resources concurrently, leading to
unpredictable outcomes. Java provides two ways to achieve synchronization:
- **Synchronized Methods**: The `synchronized` keyword ensures that
only one thread can execute a method at a time. The thread obtains a
lock on the object before executing the synchronized method.
```java
Synchronized void increment() {
Count++;
```
- **Synchronized Blocks**: It allows more fine-grained control than
synchronized methods by synchronizing only specific parts of a method.
```java
Void method() {
Synchronized (this) {
// Only this block is synchronized
```
- **Intrinsic Locks**: Every object in Java has an intrinsic lock (or monitor)
associated with it. When a thread enters a synchronized method or
block, it obtains the lock for that object.
**Common Synchronization Problems**:
- **Deadlock**: When two or more threads are waiting indefinitely for each
other to release locks, causing them to get stuck.
- **Thread Safety**: Using synchronization ensures that shared resources
are accessed safely by multiple threads.
### 5. **wait(), notify(), notifyAll() Methods**
Java provides methods like `wait()`, `notify()`, and `notifyAll()` for thread
communication, allowing threads to coordinate their actions.
- **`wait()`**: This method makes the calling thread give up its monitor
and enter a waiting state until another thread calls `notify()` or
`notifyAll()` on the same object.
```java
Synchronized(obj) {
[Link](); // The thread waits until it’s notified
```
- **`notify()`**: Wakes up a single thread that is waiting on the object’s
monitor.
```java
Synchronized(obj) {
[Link](); // Wakes up one waiting thread
```
- **`notifyAll()`**: Wakes up all the threads waiting on the object’s
monitor.
```java
Synchronized(obj) {
[Link](); // Wakes up all waiting threads
```
**Explanation**:
These methods are used to coordinate multiple threads where one thread
might wait for a condition to be met (using `wait()`), and another thread
notifies the waiting thread(s) when the condition is fulfilled (using `notify()`
or `notifyAll()`).
These answers give detailed insights into multithreading in Java, focusing on
key concepts, examples, and explanations, appropriate for 5-mark questions
in an exam.