Wednesday, December 11, 2019

How To Interruption Thread Inwards Coffee Using Sleep() Together With Timeunit Example

There are multiple ways to suspension or halt the execution of currently running thread, but putting the thread into slumber state using Thread.sleep() method is the correct means to innovate pause. Some people would say, why non usage hold back together with notify?. Using those methods only for pausing thread is non good. Those are the tools for a conditional hold back together with they don't depend on upon time. Influenza A virus subtype H5N1 thread blocked using wait() volition stay to hold back until the status on which it is waiting is changed. Yes, you lot tin seat timeout in that location but the operate of wait() method is different, they are designed for inter-thread communication inwards Java. By using sleep() method, you lot suspension the electrical flow for roughly given time. You should never usage sleep() inwards house of wait() together with notify() together with vice-versa. There is roughly other argue why to hold back together with notify should non last used to suspension the thread, a they bespeak lock. You tin solely telephone phone them from a synchronized method or block together with acquire together with unloose a lock is non cheap.

More importantly, why create you lot bespeak to innovate lock only for pausing thread? Also i of the commutation departure betwixt wait() together with sleep() method is that, Thread.sleep() puts the electrical flow thread on hold back but doesn't unloose whatever lock it is holding, but hold back does unloose the lock it holds earlier going into blocking state.

In short, multi-threading is non easy, even a uncomplicated delineate of piece of work similar creating a thread, stopping a thread or pausing a thread require a proficient cognition of Java API. You bespeak to usage the correct method at the correct place. If you lot are serious virtually mastering multi-threading together with concurrency, I would advise to read Java Concurrency inwards Practice twice together with create every illustration given on that book. That majority volition alter how you lot expect a work from multi-threading perspective.




How to suspension Thread using Sleep inwards Java

Here is our sample Java programme to suspension a running thread using Thread.sleep() together with TimeUnit.sleep() method inwards Java. In this uncomplicated program, nosotros accept 2 thread, principal thread which is started past times JVM together with executes your Java programme past times invoking the public static void main(String args[]) method. The minute thread is "T1", which nosotros accept created together with it is used to run our game loop. The Runnable delineate of piece of work nosotros passed to this thread has an infinite piece loop, which runs until stopped. If you lot expect at closely, nosotros accept used a volatile modifier to halt a thread inwards Java.

Main thread showtime starts the thread together with and thence stops it past times using stop() method inwards our Game course of written report which extends Runnable. When T1 starts it goes into a game loop together with and thence pauses for 200 milliseconds. In betwixt nosotros accept also seat the principal thread to slumber past times using TimeUnit.sleep() method. So principal thread tin hold back for roughly fourth dimension together with inwards the meantime, T1 volition resume together with finished. If you lot accept non read already together with thence you lot must read Java Concurrency inwards Practice to hit a comprehensive agreement of multithreading inwards Java.




In i example, nosotros accept learned 2 ways to suspension a thread inwards Java, past times using Thread.sleep() method together with TimeUnit.sleep() method. The declaration you lot move past times to sleep() is fourth dimension to slumber inwards a millisecond but that's non clear from code. This is where TimeUnit course of written report helps.

You acquire TimeUnit illustration for a specific fourth dimension unit of measurement e.g. TimeUnit.SECONDS or TimeUnit.MICROSECOND earlier calling slumber on it. You tin meet its much to a greater extent than clear how long a thread volition hold back now. In short, usage TimeUnit class' sleep() method to suspension a thread because it's to a greater extent than readable. To larn to a greater extent than virtually TimeUnit class, meet my post service why to prefer TimeUnit inwards Java.


Thread.sleep() together with TimeUnit Example

import static java.lang.Thread.currentThread;  import java.util.concurrent.TimeUnit;  /**  * Java Program to demonstrate how to suspension a thread inwards Java.  * There is no suspension method, but in that location are multiple means to suspension  * a thread for curt catamenia of time. Two pop means is either  * past times using Thread.sleep() method or TimeUnit.sleep() method.  *   * @author java67  */  public class ThreadPauseDemo {      public static void main(String args[]) throws InterruptedException {         Game game = new Game();          Thread t1 = new Thread(game, "T1");         t1.start();                  //Now, let's halt our Game thread         System.out.println(currentThread().getName() + " is stopping game thread");         game.stop();                  //Let's hold back to meet game thread stopped          TimeUnit.MILLISECONDS.sleep(200);                  System.out.println(currentThread().getName() + " is finished now");     } }  class Game implements Runnable{     private volatile boolean isStopped = false;          public void run() {                  while(!isStopped){             System.out.println("Game thread is running.....");                         System.out.println("Game thread is forthwith going to pause");                          try {                 Thread.sleep(200);             } catch (InterruptedException e) {                                e.printStackTrace();             }                          System.out.println("Game thread is forthwith resumed ..");         }                  System.out.println("Game thread is stopped....");     }          public void stop(){         isStopped = true;     } }  Output principal is stopping game thread Game thread is running..... Game thread is forthwith going to suspension Game thread is forthwith resumed .. Game thread is stopped.... principal is finished forthwith 


Important points virtually sleep() method :

Now you lot know how to seat a thread on slumber or pause, it's fourth dimension to know roughly technical details virtually Thread.sleep() method inwards Java.

static method together with it ever puts the electrical flow thread to sleep.

2) You tin wake-up a sleeping thread past times calling interrupt() method on the thread which is sleeping.

3) The slumber method doesn't guarantee that the thread volition slumber for precisely that many milliseconds, its accuracy depends on upon organization timers together with it's possible for a thread to woke before.

4) It doesn't unloose the lock it has acquired.


That's all virtually how to seat a thread on suspension past times using Thread.sleep() method together with TimeUnit's sleep() method. It's ameliorate to usage TimeUnit course of written report because it improves readability of code, but its also non hard to recall that declaration passed to sleep() method is inwards millisecond. Two commutation things to recall is that Thread.sleep() is a static method together with ever put the electrical flow thread to sleep, together with it doesn't unloose whatever lock held past times sleeping thread.

Further Learning
Multithreading together with Parallel Computing inwards Java
article)
  • What is the departure betwixt Thread together with Runnable inwards Java? (answer)
  • What is the departure betwixt Process together with Thread inwards Java? (answer)
  • Understanding the departure betwixt wait() together with sleep() inwards Thread? (answer)
  • What is the departure betwixt Callable together with Runnable inwards Java? (answer)
  • What is the departure betwixt wait() together with yield() method inwards Java? (answer)
  • When to usage notify() together with notifyAll() inwards Java? (answer)
  • What is the departure betwixt CyclicBarrier together with CountDownLatch inwards Java? (answer)
  • The departure betwixt yield() together with sleep() method inwards Java? (answer)

  • Thanks for reading this article, if you lot similar this tutorial together with thence delight portion alongside your friends together with colleagues.

    No comments:

    Post a Comment