Java’s Thread Methods
Get and Set Methods
1. Thread.getThreadGroup()
The getThreadGroup() method is used to get the thread group to which the thread belongs. For example:
1 | ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); |
2. Thread.setDaemon()
The setDaemon(boolean on) method is used to set the thread as a daemon thread. Daemon threads automatically exit when the main thread finishes. For example:
1 | Thread daemonThread = new Thread(() -> { |
Enquiry Methods
Thread.isAlive()
The isAlive() method is used to check if the thread is alive (not yet terminated). For example:
1 | Thread myThread = new Thread(() -> { |
Action Methods
1. Thread.interrupt()
The interrupt() method is used to interrupt a thread. It sets the thread’s interrupt status but does not immediately terminate the thread. The thread needs to check its interrupt status and respond appropriately to exit safely. For example:
1 | Thread myThread = new Thread(() -> { |
Static Methods
1. Thread.currentThread()
The currentThread() method is used to get the currently executing thread. For example:
1 | Thread currentThread = Thread.currentThread(); |
2. Thread.activeCount()
The activeCount() method is used to get the number of active threads in the current thread group. For example:
1 | ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); |
3. Thread.dumpStack()
The dumpStack() method prints the stack trace of the current thread to the standard error stream (System.err). This is useful for debugging and analyzing problems such as exceptions or deadlocks. For example:
1 | Thread.dumpStack(); |
Example Code Demonstrating All Methods
Below is a comprehensive example that demonstrates the usage of various Thread methods:
1 | public class ThreadMethodsExample { |
This example demonstrates how to:
- Create and start a thread.
- Set a thread as a daemon thread.
- Get the thread group of the current thread.
- Check if a thread is alive.
- Interrupt a thread.
- Get the current thread.
- Get the number of active threads in the current thread group.
- Print the stack trace of the current thread.
- Wait for a thread to finish using
join().
Using these methods effectively can help manage and control the behavior of threads in a Java application.