JavaHow to Pause Thread Execution in Java

How to Pause Thread Execution in Java

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Java Programming tutorials

Thread execution control is a crucial aspect of developing robust and efficient concurrent applications in Java. Pausing thread execution at specific points can help in synchronization, coordination, and avoiding race conditions. In this programming tutorial, we will explore various techniques for pausing thread execution in Java.

Thread.sleep(): Introducing Controlled Delays in Java

The most straightforward way to pause thread execution is by using the Thread.sleep() method. This method causes the currently executing thread to sleep for a specified amount of time in milliseconds. While simple to use, it is essential to keep in mind that Thread.sleep() does not guarantee precise timing, as the operating system’s scheduling can introduce variations in the delay. Developers can use this method when they need to introduce controlled delays between thread actions, such as waiting for resources or simulating time-based events.

Here is some sample code that utilizes Thread.sleep() to pause for 500 milliseconds between the incrementing and printing of a variable:

  class ThreadSleepExample extends Thread {    
    public void run(){    
      for(int i=1;i&lt=5;i++){   
        try {
          Thread.sleep(500);
        }
        catch(InterruptedException e) {
          System.out.println(e);
        }    
        System.out.println(i);    
      }    
    }    
    public static void main(String args[]) {    
      ThreadSleepExample t1 = new ThreadSleepExample();    
      ThreadSleepExample t2 = new ThreadSleepExample();    
         
      t1.start();    
      t2.start();    
    }    
  }   

/* 
Outputs:
1
1
2
2
3
3
4
4
5
5
*/ 

Read: Best Collaboration Tools for Java Developers

Object.wait(): Synchronization and Inter-Thread Communication

The Object.wait() method is used for inter-thread communication and synchronization. It allows a thread to wait until another thread invokes notify() or notifyAll() on the same object. This technique is especially useful when multiple threads need to coordinate their actions based on certain conditions.

Here is a sample Java program to demonstrate how to use the Object.wait() method:

package com.developer;

public class WaitExample {
  public static void main(String[] args) {
    final Object lock = new Object(); // Shared lock object
    
    // Thread 1 - Waits for a signal to proceed
    Thread thread1 = new Thread(() -> {
      synchronized (lock) {
        System.out.println("Thread 1 is waiting...");
        try {
          lock.wait(); // Thread 1 waits until notified
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println("Thread 1 has been notified and resumed.");
      }
    });

    // Thread 2 - Notifies Thread 1 to proceed
    Thread thread2 = new Thread(() -> {
      try {
        Thread.sleep(2000); // Wait for 2 seconds
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (lock) {
        System.out.println("Thread 2 is notifying Thread 1.");
        lock.notify(); // Notifying Thread 1 to continue
      }
    });

    thread1.start();
    thread2.start();
    
    try {
      thread1.join();
      thread2.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    
    System.out.println("Main thread finished.");
  }
}
/*
Output:
Thread 1 is waiting...
Thread 2 is notifying Thread 1.
Thread 1 has been notified and resumed.
Main thread finished.
*/

In this example:

  1. Thread 1 enters a synchronized block using the shared lock object and then calls lock.wait(). This causes Thread 1 to release the lock and wait until another thread calls lock.notify() or lock.notifyAll() on the same lock object.
  2. Thread 2 starts after a delay of 2 seconds. It also enters a synchronized block using the same lock object and then calls lock.notify() to wake up Thread 1.
  3. After Thread 2 notifies Thread 1, Thread 1 resumes its execution and prints a message.

Read: Best Tools for Java Mobile Development

Thread.yield(): Giving Up CPU Time in Java

The Thread.yield() method suggests to the thread scheduler that the current thread is willing to yield its current time slice. While it does not guarantee a pause, it might allow other threads with equal or higher priority to run. However, it is important to note that relying solely on Thread.yield() for thread coordination is not recommended, as it depends on the thread scheduler’s behavior and might not provide consistent results across different Java Virtual Machine (JVM) implementations.

Here is some example code showing how to use Thread.yield() in Java:

package com.developer;

public class YieldExample {
  public static void main(String[] args) {
    Thread thread1 = new Thread(() -> {
      for (int i = 1; i <= 5; i++) {
        System.out.println("Thread 1 - Iteration " + i);
        Thread.yield(); // Yielding thread execution
      }
    });

    Thread thread2 = new Thread(() -> {
      for (int i = 1; i <= 5; i++) {
        System.out.println("Thread 2 - Iteration " + i);
        Thread.yield(); // Yielding thread execution
      }
    });

    thread1.start();
    thread2.start();
  }
}

/*
Output:
Thread 1 - Iteration 1
Thread 2 - Iteration 1
Thread 1 - Iteration 2
Thread 1 - Iteration 3
Thread 2 - Iteration 2
Thread 2 - Iteration 3
Thread 2 - Iteration 4
Thread 2 - Iteration 5
Thread 1 - Iteration 4
Thread 1 - Iteration 5
*/

In the above program:

  • Thread 1 and Thread 2 are created, each with a simple loop that prints iterations.
  • Within each loop iteration, the Thread.yield() method is called. This suggests to the thread scheduler that the current thread is willing to yield its current time slice, giving other threads a chance to execute.

When we run this example, we can see that both threads are yielding their execution alternatively, allowing each other to run. However, it’s important to note that the actual behavior of Thread.yield() can vary depending on the JVM implementation and the operating system’s thread scheduler. In some cases, it might not result in a significant change in execution order, especially if one thread has higher priority.

It is also important to remember that, while Thread.yield() can be useful in certain scenarios to provide a hint to the thread scheduler, it is generally not the primary way to achieve synchronization and coordination between threads. More robust synchronization mechanisms, like wait(), notify(), locks, and advanced concurrency utilities, are often preferred for precise control over thread interactions.

Final Thoughts on How to Pause Thread Execution in Java

Managing thread execution pauses is a critical skill for Java developers building concurrent applications. Whether you are introducing controlled delays, synchronizing threads, or utilizing advanced concurrency utilities, understanding the techniques discussed in this article will empower you to create robust, efficient, and responsive multi-threaded applications in Java. Remember that the choice of technique depends on your specific requirements, and careful consideration is needed to ensure optimal performance and synchronization.

Next Steps

Now that you have a better understanding of the different methods developers can use to pause thread execution, you might want to consider reading some of our other Java tutorials focusing on threading, multithreading, and concurrency. We highlight a few below to help get you started:

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories