Thread in Java ?
jab `ref1.run()` aur `ref2.run()` ko directly call karte ho, tab wo methods main thread mein sequentially execute hote hain, alag-alag threads mein nahi. Iska matlab hai ki aap actual multithreading nahi kar rahe ho.
* Thread class has only the way we can achieve multithreading
* We can Create Thread using Thread class and Runnable Interface
* Thread class has many method :
* join() -> it will wait for completion of Thread
* sleep(milisec) -> it will wait after statment for given miliseconds
* Runnable is the FunctionalInterface it means we can use Anonymous inner class and Lambda Expressions (only one non - abstract method is there which is run())
***Multithreading only possible using start() method of Thread class
Java mein true multithreading achieve karne ke liye, aapko `Thread` class ka use karke `Runnable` instances ko alag threads mein start karna padta hai. Main difference yeh hai:
- **Direct Call (`run` method)**:
- `ref1.run()` aur `ref2.run()` ko call karne se yeh methods main thread mein sequentially execute hote hain.
- No concurrent execution.
- **Using Threads (`start` method)**:
- `new Thread(ref1).start()` aur `new Thread(ref2).start()` ko call karne se yeh methods alag threads mein concurrently execute hote hain.
- Potential race conditions can occur if the methods are not synchronized.
Example:
### Sequential Execution (No Multithreading):
```java
ref1.run(); // Executes in the main thread
ref2.run(); // Executes in the main thread after ref1 finishes
```
### Concurrent Execution (With Multithreading):
```java
Thread thread1 = new Thread(ref1);
Thread thread2 = new Thread(ref2);
thread1.start(); // Executes in a new thread
thread2.start(); // Executes in another new thread
```
### Complete Example with Threads:
```java
class C {
int c;
public synchronized void count() {
c++;
}
}
public class Synchronise_meth {
public static void main(String[] args) {
C c_ref = new C();
Runnable ref1 = () -> {
for (int i = 0; i < 10000; i++) {
c_ref.count();
}
};
Runnable ref2 = () -> {
for (int i = 0; i < 10000; i++) {
c_ref.count();
}
};
Thread thread1 = new Thread(ref1);
Thread thread2 = new Thread(ref2);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(c_ref.c);
}
}
```
Is code mein `thread1` aur `thread2` alag-alag threads mein concurrently execute honge, aur `join` method ensure karta hai ki main thread wait kare jab tak dono threads apna execution complete nahi kar lete. Synchronized `count` method use karke aap thread safety ensure kar sakte ho, varna race conditions ke wajah se incorrect results mil sakte hain.
All methods :
Sure! The `Thread` class in Java provides several methods that allow you to manage thread lifecycle and control its execution. Here are the main methods, along with explanations:
### Thread Management Methods
1. **`start()`**:
- Begins the execution of the thread. The JVM calls the `run()` method of this thread.
- Transitions the thread from the `New` state to the `Runnable` state.
- Example:
```java
Thread t = new Thread(runnableInstance);
t.start();
```
2. **`run()`**:
- The entry point for the thread. This method contains the code that constitutes the new thread.
- Typically, you override this method when creating a custom thread by extending the `Thread` class or implementing the `Runnable` interface.
- Example:
```java
@Override
public void run() {
// Code to be executed in the new thread
}
```
3. **`join()`**:
- Waits for this thread to die. The calling thread will be blocked until the referenced thread terminates.
- Example:
```java
t1.join();
```
4. **`sleep(long millis)`**:
- Causes the current thread to suspend execution for the specified period (in milliseconds).
- Example:
```java
try {
Thread.sleep(1000); // Sleeps for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
```
5. **`interrupt()`**:
- Interrupts the thread. If the thread is in a blocked state (such as waiting or sleeping), it will throw an `InterruptedException`.
- Example:
```java
t1.interrupt();
```
6. **`isInterrupted()`**:
- Tests whether the thread has been interrupted.
- Example:
```java
if (t1.isInterrupted()) {
// Handle interruption
}
```
7. **`interrupted()`** (static method):
- Tests whether the current thread has been interrupted. It also clears the interrupted status.
- Example:
```java
if (Thread.interrupted()) {
// Handle interruption
}
```
8. **`setPriority(int newPriority)`**:
- Changes the priority of the thread. The priority is a value between `Thread.MIN_PRIORITY` (1) and `Thread.MAX_PRIORITY` (10), with `Thread.NORM_PRIORITY` (5) as the default.
- Example:
```java
t1.setPriority(Thread.MAX_PRIORITY);
```
9. **`getPriority()`**:
- Returns the priority of the thread.
- Example:
```java
int priority = t1.getPriority();
```
10. **`setName(String name)`**:
- Changes the name of the thread.
- Example:
```java
t1.setName("MyThread");
```
11. **`getName()`**:
- Returns the name of the thread.
- Example:
```java
String name = t1.getName();
```
12. **`getId()`**:
- Returns the thread's ID, which is a unique identifier for the thread.
- Example:
```java
long id = t1.getId();
```
13. **`getState()`**:
- Returns the state of the thread, such as `NEW`, `RUNNABLE`, `BLOCKED`, `WAITING`, `TIMED_WAITING`, or `TERMINATED`.
- Example:
```java
Thread.State state = t1.getState();
```
14. **`isAlive()`**:
- Tests if the thread is alive. A thread is alive if it has been started and has not yet died.
- Example:
```java
if (t1.isAlive()) {
// The thread is still running
}
```
15. **`yield()`** (static method):
- Causes the currently executing thread object to temporarily pause and allow other threads to execute.
- Example:
```java
Thread.yield();
```
16. **`setDaemon(boolean on)`**:
- Marks the thread as a daemon thread or a user thread. A daemon thread runs in the background and does not prevent the JVM from exiting when all user threads finish their execution.
- Example:
```java
t1.setDaemon(true);
```
17. **`isDaemon()`**:
- Tests if the thread is a daemon thread.
- Example:
```java
if (t1.isDaemon()) {
// The thread is a daemon thread
}
18. **
notify()
Method
- Purpose: Used to wake up a single thread that is waiting on the object's monitor (waiting due to a call to
wait()
). - Usage: Typically used in a synchronized context.
- Scenario: When a thread calls
wait()
on an object, it releases the lock on the object and enters theWAITING
state. Another thread can callnotify()
(ornotifyAll()
) on the same object to wake up the waiting thread. - Behavior: The awakened thread does not immediately proceed; it must reacquire the object's monitor lock, which may require waiting if other threads hold the lock.
19. **sleep()
Method
- Purpose: Used to pause the execution of the current thread for a specified period (in milliseconds).
- Usage: Can be called from any context (synchronized or not).
- Scenario: A thread voluntarily pauses its execution for a specified duration, enters the
TIMED_WAITING
state, and automatically resumes after the specified time has elapsed. - Behavior: The sleeping thread resumes execution after the sleep period ends without needing any external signal.
```
### Example of Creating and Managing a Thread
Here is an example that demonstrates some of these methods in action:
```java
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
}
}
}
}
public class ThreadMethodsExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setName("Thread 1");
t2.setName("Thread 2");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Both threads have finished execution.");
}
}
```
In this example:
- We create a custom thread by extending the `Thread` class.
- We override the `run()` method to define the thread's behavior.
- We set names and priorities for the threads.
- We start the threads using the `start()` method.
- We use the `join()` method to wait for both threads to finish.
By understanding these methods, you can effectively manage and control the behavior of threads in your Java programs.
Comments
Post a Comment