Thursday, August 17, 2023
HomeSoftware DevelopmentPause Thread Execution in Java

Pause Thread Execution in Java


Developer.com content material and product suggestions are editorially unbiased. We might earn cash once you click on on hyperlinks to our companions. Be taught Extra.

Java Programming tutorials

Thread execution management is a vital facet of creating strong and environment friendly concurrent purposes in Java. Pausing thread execution at particular factors may also help in synchronization, coordination, and avoiding race circumstances. On this programming tutorial, we’ll discover varied strategies for pausing thread execution in Java.

Thread.sleep(): Introducing Managed Delays in Java

Essentially the most easy option to pause thread execution is through the use of the Thread.sleep() methodology. This methodology causes the presently executing thread to sleep for a specified period of time in milliseconds. Whereas easy to make use of, it’s important to needless to say Thread.sleep() doesn’t assure exact timing, because the working system’s scheduling can introduce variations within the delay. Builders can use this methodology when they should introduce managed delays between thread actions, akin to ready for assets or simulating time-based occasions.

Right here is a few pattern code that makes use of 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++){   
        strive {
          Thread.sleep(500);
        }
        catch(InterruptedException e) {
          System.out.println(e);
        }    
        System.out.println(i);    
      }    
    }    
    public static void important(String args[]) {    
      ThreadSleepExample t1 = new ThreadSleepExample();    
      ThreadSleepExample t2 = new ThreadSleepExample();    
         
      t1.begin();    
      t2.begin();    
    }    
  }   

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

Learn: Greatest Collaboration Instruments for Java Builders

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

The Object.wait() methodology is used for inter-thread communication and synchronization. It permits a thread to attend till one other thread invokes notify() or notifyAll() on the identical object. This method is very helpful when a number of threads have to coordinate their actions primarily based on sure circumstances.

Here’s a pattern Java program to exhibit methods to use the Object.wait() methodology:

bundle com.developer;

public class WaitExample {
  public static void important(String[] args) {
    remaining Object lock = new Object(); // Shared lock object
    
    // Thread 1 - Waits for a sign to proceed
    Thread thread1 = new Thread(() -> {
      synchronized (lock) {
        System.out.println("Thread 1 is ready...");
        strive {
          lock.wait(); // Thread 1 waits till 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(() -> {
      strive {
        Thread.sleep(2000); // Wait for two seconds
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (lock) {
        System.out.println("Thread 2 is notifying Thread 1.");
        lock.notify(); // Notifying Thread 1 to proceed
      }
    });

    thread1.begin();
    thread2.begin();
    
    strive {
      thread1.be part of();
      thread2.be part of();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    
    System.out.println("Major thread completed.");
  }
}
/*
Output:
Thread 1 is ready...
Thread 2 is notifying Thread 1.
Thread 1 has been notified and resumed.
Major thread completed.
*/

On this instance:

  1. Thread 1 enters a synchronized block utilizing the shared lock object after which calls lock.wait(). This causes Thread 1 to launch the lock and wait till one other thread calls lock.notify() or lock.notifyAll() on the identical lock object.
  2. Thread 2 begins after a delay of two seconds. It additionally enters a synchronized block utilizing the identical lock object after which calls lock.notify() to get up Thread 1.
  3. After Thread 2 notifies Thread 1, Thread 1 resumes its execution and prints a message.

Learn: Greatest Instruments for Java Cell Growth

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

The Thread.yield() methodology suggests to the thread scheduler that the present thread is prepared to yield its present time slice. Whereas it doesn’t assure a pause, it’d enable different threads with equal or greater precedence to run. Nevertheless, you will need to word that relying solely on Thread.yield() for thread coordination is just not beneficial, because it will depend on the thread scheduler’s habits and won’t present constant outcomes throughout totally different Java Digital Machine (JVM) implementations.

Right here is a few instance code displaying methods to use Thread.yield() in Java:

bundle com.developer;

public class YieldExample {
  public static void important(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.begin();
    thread2.begin();
  }
}

/*
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
*/

Within the above program:

  • Thread 1 and Thread 2 are created, every with a easy loop that prints iterations.
  • Inside every loop iteration, the Thread.yield() methodology known as. This implies to the thread scheduler that the present thread is prepared to yield its present time slice, giving different threads an opportunity to execute.

After we run this instance, we are able to see that each threads are yielding their execution alternatively, permitting one another to run. Nevertheless, it’s essential to notice that the precise habits of Thread.yield() can fluctuate relying on the JVM implementation and the working system’s thread scheduler. In some circumstances, it won’t lead to a major change in execution order, particularly if one thread has greater precedence.

It’s also essential to keep in mind that, whereas Thread.yield() might be helpful in sure situations to offer a touch to the thread scheduler, it’s typically not the first option to obtain synchronization and coordination between threads. Extra strong synchronization mechanisms, like wait(), notify(), locks, and superior concurrency utilities, are sometimes most popular for exact management over thread interactions.

Remaining Ideas on Pause Thread Execution in Java

Managing thread execution pauses is a essential talent for Java builders constructing concurrent purposes. Whether or not you might be introducing managed delays, synchronizing threads, or using superior concurrency utilities, understanding the strategies mentioned on this article will empower you to create strong, environment friendly, and responsive multi-threaded purposes in Java. Do not forget that the selection of method will depend on your particular necessities, and cautious consideration is required to make sure optimum efficiency and synchronization.

Subsequent Steps

Now that you’ve got a greater understanding of the totally different strategies builders can use to pause thread execution, you may wish to think about studying a few of our different Java tutorials specializing in threading, multithreading, and concurrency. We spotlight a number of under to assist get you began:



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments