Thread Methods and their use cases
Java provides several methods in the Thread class to manage and control threads. These methods allow developers to create, start, pause, resume, and terminate threads effectively. Below is a detailed explanation of the most commonly used thread methods and their use cases.
start()
- Description: Starts a new thread and invokes the
run()method. This method transitions the thread from the "new" state to the "runnable" state. - Use Case: Used to begin the execution of a thread.
Example:
Thread thread = new Thread(() -> System.out.println("Thread is running"));
thread.start();
run()
- Description: Contains the code that a thread executes. It is called automatically when the
start()method is invoked. - Use Case: Override this method to define the task for the thread.
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
sleep(long milliseconds)
- Description: Pauses the execution of the current thread for the specified time (in milliseconds).
- Use Case: Used to delay thread execution or simulate a waiting period.
Example
try {
Thread.sleep(1000); // Pauses for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
join()
- Description: Waits for a thread to finish its execution before proceeding with the next line of code.
- Use Case: Used when one thread depends on the completion of another thread.
Example
Thread thread = new Thread(() -> System.out.println("Thread finished"));
thread.start();
try {
thread.join(); // Waits for the thread to complete
System.out.println("Main thread continues");
} catch (InterruptedException e) {
e.printStackTrace();
}
isAlive()
- Description: Checks if a thread is still running.
- Use Case: Used to verify whether a thread has completed its execution.
Example:
Thread thread = new Thread(() -> System.out.println("Thread is running"));
thread.start();
System.out.println("Is thread alive? " + thread.isAlive());
getName() and setName(String name)
- Description:
getName()retrieves the name of the thread, andsetName()sets a custom name for the thread. - Use Case: Used to identify threads, especially in multithreaded applications.
Thread thread = new Thread(() -> System.out.println("Thread is running"));
thread.setName("MyThread");
thread.start();
System.out.println("Thread name: " + thread.getName());
// Output
// Thread name MyThread
getPriority() and setPriority(int priority)
- Description:
getPriority()retrieves the priority of a thread, andsetPriority()sets the priority (values range fromThread.MIN_PRIORITY(1) toThread.MAX_PRIORITY(10)). - Use Case: Used to control the execution order of threads (though thread scheduling is platform-dependent).
Thread thread = new Thread(() -> System.out.println("Thread is running"));
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
System.out.println("Thread priority: " + thread.getPriority()); // 10
interrupt()
- Description: Interrupts a thread, signaling it to stop or perform a specific action. The thread must handle the interruption explicitly.
- Use Case: Used to stop a thread or signal it to perform a specific task.
Thread thread = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
});
thread.start();
thread.interrupt(); // Interrupts the thread
yield()
- Description: Temporarily pauses the execution of the current thread to allow other threads of the same priority to execute.
- Use Case: Used to improve thread scheduling and allow other threads to execute.
Thread thread = new Thread(() -> {
System.out.println("Thread yielding");
Thread.yield();
System.out.println("Thread resumed");
});
thread.start();
currentThread()
- Description: Returns a reference to the currently executing thread.
- Use Case: Used to get information about the thread currently running.
Thread thread = Thread.currentThread();
System.out.println("Current thread: " + thread.getName());
setDaemon(boolean t) and isDaemon()
- Description:
setDaemon()marks a thread as a daemon thread, andisDaemon()checks if a thread is a daemon. Daemon threads run in the background and terminate when all user threads finish. - Use Case: Used for background tasks like garbage collection.
Thread thread = new Thread(() -> System.out.println("Daemon thread running"));
thread.setDaemon(true);
thread.start();
System.out.println("Is daemon: " + thread.isDaemon());
stop() (Depricatted)
- Description: Forces a thread to stop execution immediately.
- Use Case: Not recommended as it can leave resources in an inconsistent state. Use
interrupt()instead.
