Skip to main content

Thread Methods & Priority

The java.lang.Thread class provides a multitude of methods to control and manipulate the behavior of threads. Let's look at the most commonly used methods for pausing, yielding, and joining threads, as well as how to assign priorities.


1. sleep() Method

The sleep(long milliseconds) method pauses the execution of the current thread for the specified duration.

  • It is a static method, so it always affects the currently executing thread.
  • It throws a checked exception called InterruptedException, which must be caught or declared.

Example

public class LabThread4 extends Thread {

public void run() {
for (int i = 1; i <= 3; i++) {
try {
// Pause execution for 1000ms (1 second)
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(
"Thread ID: " + Thread.currentThread().getId() + " - Count: " + i
);
}
}

public static void main(String args[]) {
LabThread4 t1 = new LabThread4();
LabThread4 t2 = new LabThread4();

t1.start();
t2.start();
}
}

[!NOTE] t1 and t2 will execute concurrently, both pausing for one second at each iteration.


2. join() Method

The join() method forces the current thread to wait until the thread on which join() was called completes its execution (dies).

  • This is very useful when you have a sequence of tasks and a thread depends on the result of another thread.
  • It also throws an InterruptedException.

Example

public class LabThread5 extends Thread {

public void run() {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(
Thread.currentThread().getName() + " is running: " + i
);
}
}

public static void main(String args[]) {
LabThread5 t1 = new LabThread5();
LabThread5 t2 = new LabThread5();
LabThread5 t3 = new LabThread5();

t1.setName("Thread-1");
t2.setName("Thread-2");
t3.setName("Thread-3");

t1.start();
try {
// The main thread will wait for t1 to finish before executing the next lines
t1.join();
} catch (InterruptedException e) {
System.out.println(e);
}

// t2 and t3 will start ONLY after t1 has completely finished
t2.start();
t3.start();
}
}

3. yield() Method

The yield() method causes the currently executing thread object to temporarily pause and allow other threads of the same priority to execute.

  • It is a request to the thread scheduler, which might be ignored depending on the JVM and OS implementation.
  • It moves the thread from the Running state back to the Runnable state.

Thread Priority

Each thread in Java has a priority that helps the operating system determine the order in which threads are scheduled.

Java thread priorities are integers ranging from 1 to 10:

  • Thread.MIN_PRIORITY = 1
  • Thread.NORM_PRIORITY = 5 (Default for the Main thread)
  • Thread.MAX_PRIORITY = 10

Setting and Getting Priority

You can alter the priority of a thread using the setPriority(int priority) method and check it using getPriority().

public class LabThread6 extends Thread {

public void run() {
System.out.println(
"Running thread name: " + Thread.currentThread().getName()
);
System.out.println(
"Running thread priority: " + Thread.currentThread().getPriority()
);
}

public static void main(String args[]) {
LabThread6 t1 = new LabThread6();
LabThread6 t2 = new LabThread6();

t1.setName("LowPriorityThread");
t2.setName("HighPriorityThread");

// Setting priorities
t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.MAX_PRIORITY); // Priority 10

t1.start();
t2.start();
}
}

[!WARNING] Thread priority does not guarantee execution order! It merely provides a hint to the thread scheduler. Depending on the OS, a lower priority thread could occasionally run before a higher priority thread.


Daemon Threads

A Daemon Thread is a low-priority service thread that runs in the background to perform tasks like garbage collection.

  • Its life depends on user threads (non-daemon threads). If all user threads finish their execution, the JVM terminates itself automatically, destroying any running daemon threads.
  • You can make a thread daemon by calling setDaemon(true) before calling start().
public class LabThread7 extends Thread {

public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("Daemon thread is running...");
} else {
System.out.println("User thread is running...");
}
}

public static void main(String[] args) {
LabThread7 t1 = new LabThread7();
LabThread7 t2 = new LabThread7();

// Setting t1 as a daemon thread
t1.setDaemon(true);

t1.start();
t2.start();
}
}