Java Threading Methods: A Complete Guide

Developer.com content and product recommendations are editorially independent. We may earn money when you click on links to our partners. Learn more.
Java threads allow multiple tasks to run simultaneously within a single program. This programming tutorial explores various methods of thread management in Java. In particular, we will review methods that deal with thread states and properties, as well as their synchronization and interruption. In a later part, we’ll cover methods of controlling thread priority, daemon threads, sleeping and waiting, and a few miscellaneous methods that don’t fit into any of the above categories.
How to start a discussion thread in Java
to start()
THE to start() The method starts the execution of a thread. He calls the run()
method defined in your thread class or executable object. Invoke run()
directly will not start a new thread, so it is crucial to use start()
. Here is sample code showing its usage:
public class Main {
public static void main(String() args) {
Thread myThread = new Thread(new MyRunnable());
myThread.start();
}
}
run()
THE run()
The method contains the code that will be executed in the thread. It must be canceled when extending the Thread
class or implementation of the Runnable
interface.
class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a runnable.");
}
}
Thread states and properties
getState()
THE getState() The method returns the current state of the thread as an integer. The possible states are:
- NEW: The thread has been created but has not yet started.
- EXECUTIVE: The thread is actively running or is ready to be executed.
- BLOCKED: The thread is stuck, waiting for a monitor lock.
- WAITING: The thread waits indefinitely for another thread to perform a specific action.
- TIMED_WAITING: The thread waits for a specified period of time.
- FINISHED: The thread has completed execution and exited.
Here is a code example illustrating the thread states above:
Thread myThread = new Thread(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println(myThread.getState()); // Output: NEW myThread.start(); System.out.println(myThread. getState()); // Output: RUNNABLE try { myThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(myThread. getState()); // Output: TERMINATED
In this example, we created a discussion thread (my discussion thread), started it, then checked its status at different points in its lifecycle.
is alive()
THE is alive() method checks if the thread is alive. A thread is considered alive if it has been started and has not yet ended. He returns TRUE if the thread is alive, and FAKE Otherwise.
In the following code example, we create a new thread (my discussion thread) but I haven’t started it yet. We then check if the thread is alive using the is alive() method, which will return FAKE. After starting the thread, we check again, and this time it will return TRUE:
Thread myThread = new Thread(); System.out.println(myThread.isAlive()); // Output: false myThread.start(); System.out.println(myThread. isAlive()); // Output: true
getName()
THE getName() The method returns the thread name.
In this Java code example, we create a new thread (my discussion thread) without specifying a name. THE getName() The method is used to retrieve and print the default name of the thread, which will look something like Subject-0:
Thread myThread = new Thread(); System.out.println(myThread.getName()); // Output: Thread-0
setName()
THE setName() The method sets the thread name.
In the following code example, we create a new thread (my discussion thread) then use setName() to set a custom name for the thread. We then use getName() again to retrieve and print the custom name:
Thread myThread = new Thread(); myThread.setName("CustomThread"); System.out.println(myThread. getName()); // Output: CustomThread
getId()
THE getID() The method returns the unique ID of the thread.
In this example, we create a new thread (my discussion thread) then use getId() to retrieve and print the unique ID assigned to the discussion thread. The value will depend on the platform:
Thread myThread = new Thread(); System.out.println(myThread.getId()); // Output: A unique identifier (platform-dependent)
getState()
THE getState() The method returns the current state of the thread as enumeration value, which provides a more human-readable representation compared to the integer values ​​returned by getState().
In the code example below, we create a new thread (my discussion thread) then use getState() to retrieve and print the current state of the thread. We also show how to get the state name using name()who will be NEW in this case:
Thread myThread = new Thread(); System.out.println(myThread.getState()); // Output: NEW System.out.println(myThread. getState().name()); // Output: NEW
Thread Synchronization and Interrupting in Java
join()
THE join() The method allows one thread to wait for another to finish. This can be useful when you need to ensure certain tasks are completed before continuing.
In the following code example, we have two threads (thread1 And thread2) which count from 1 has 5 with a delay of 1 second between each count. THE main the thread starts these two threads:
public class JoinExample { public static void main(String() args) { Thread thread1 = new Thread(() -> { for (int i = 1; i <= 5; i++) { System.out.println("Thread 1: Count " + i); try { Thread.sleep(1000); // Simulating some work } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread2 = new Thread(() -> { for (int i = 1; i <= 5; i++) { System.out.println("Thread 2: Count " + i); try { Thread.sleep(1000); // Simulating some work } catch (InterruptedException e) { e.printStackTrace(); } } }); thread1.start(); thread2.start(); try { thread1.join(); // Main thread waits for thread1 to finish } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread 1 has completed."); } }
interrupt()
Java interrupt() The method interrupts the thread, forcing it to launch a Exception interrupted next time it will check for interrupts.
In this example, we create a thread (my discussion thread) which counts from 1 has 5 with a delay of 1 second between each count. Inside the thread we have a try-catch block to manage Exception interrupted:
public class InterruptExample { public static void main(String() args) { Thread myThread = new Thread(() -> { try { for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Thread interrupted."); } }); myThread.start(); try { Thread.sleep(3000); // Main thread sleeps for 3 seconds myThread.interrupt(); // This will interrupt myThread } catch (InterruptedException e) { e.printStackTrace(); } } }
isInterrupted()
THE isInterrupted() method Checks if the thread has been interrupted. Contrary to interrupt()this does not erase the interrupted flag.
In our next code example, we create a thread (my discussion thread) which counts from 1 has 5 with a delay of 1 second between each count. Inside the thread we have a try-catch block to manage Exception interrupted:
public class IsInterruptedExample { public static void main(String() args) { Thread myThread = new Thread(() -> { try { for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Thread interrupted."); } }); myThread.start(); try { Thread.sleep(3000); // Main thread sleeps for 3 seconds myThread.interrupt(); // This will interrupt myThread boolean interruptedStatus = myThread.isInterrupted(); // Check if interrupted System.out.println("Thread interrupted status: " + interruptedStatus); } catch (InterruptedException e) { e.printStackTrace(); } } }
There is also a static version of isInterrupted(). THE Thread.interrupted() The method checks if the current thread has been interrupted and clears the interrupted flag.
Final Thoughts on Java Threading Methods
This programming tutorial explored Java Thread methods that deal with thread states and properties, as well as their synchronization and interruption. The next part will cover methods for controlling thread priority, daemon threads, sleeping and waiting, and a few miscellaneous methods.