multi threading
multi threading
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
System.out.println(“Thread is running”);
```
```java
System.out.println(“Runnable is running”);
```
**Key Points**:
- `start()` method creates a new thread and calls the `run()` method.
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
```
- **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
t.start(); // Now the thread is in “runnable” state
```
- **Timed Waiting**: The thread is waiting for a specified period (e.g., using
`sleep()` or `join(long)` methods).
**Diagram**:
```
```
**Explanation**:
Threads in Java have several life cycle methods that control their execution.
The most important methods include:
```java
t.start();
```
- **`run()`**: This method contains the task the thread will execute. It
should not be called directly (it is called internally when `start()` is invoked).
```java
```
```java
```
- **`join()`**: This method ensures that the calling thread waits for the
thread on which `join()` is called to complete.
```java
```
**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.
```java
Count++;
```
```java
Void method() {
Synchronized (this) {
```
- **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.
- **Deadlock**: When two or more threads are waiting indefinitely for each
other to release locks, causing them to get stuck.
- **`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) {
```
```java
Synchronized(obj) {
```
```java
Synchronized(obj) {
```
**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.