How to interruption Thread inwards Java using Sleep() as well as TimeUnit Example

There are multiple ways to interruption or halt the execution of currently running thread, but putting the thread into slumber set down using Thread.sleep() method is the correct agency to innovate pause. Some people would say, why non utilisation hold off as well as notify?. Using those methods merely for pausing thread is non good. Those are the tools for a conditional hold off as well as they don't depend on upon time. Influenza A virus subtype H5N1 thread blocked using wait() volition stay to hold off until the status on which it is waiting is changed. Yes, you lot tin seat timeout in that location but the utilisation of wait() method is different, they are designed for inter-thread communication inwards Java. By using sleep() method, you lot interruption the electrical current for merely about given time. You should never utilisation sleep() inwards house of wait() as well as notify() as well as vice-versa. There is merely about other argue why to hold off as well as notify should non last used to interruption the thread, a they involve lock. You tin alone telephone band them from a synchronized method or block as well as acquire as well as loose a lock is non cheap.

More importantly, why create you lot involve to innovate lock merely for pausing thread? Also 1 of the fundamental divergence betwixt wait() as well as sleep() method is that, Thread.sleep() puts the electrical current thread on hold off but doesn't loose whatever lock it is holding, but hold off does loose the lock it holds earlier going into blocking state.

In short, multi-threading is non easy, even a uncomplicated occupation similar creating a thread, stopping a thread or pausing a thread require a practiced cognition of Java API. You involve to utilisation the correct method at the correct place. If you lot are serious nigh mastering multi-threading as well as concurrency, I would propose to read Java Concurrency inwards Practice twice as well as create every illustration given on that book. That majority volition alter how you lot expect a employment from multi-threading perspective.





How to interruption Thread using Sleep inwards Java

Here is our sample Java programme to interruption a running thread using Thread.sleep() as well as TimeUnit.sleep() method inwards Java. In this uncomplicated program, nosotros receive got 2 thread, original thread which is started yesteryear JVM as well as executes your Java programme yesteryear invoking the public static void main(String args[]) method. The minute thread is "T1", which nosotros receive got created as well as it is used to run our game loop. The Runnable occupation nosotros passed to this thread has an infinite acre loop, which runs until stopped. If you lot expect at closely, nosotros receive got used a volatile modifier to halt a thread inwards Java.

Main thread kickoff starts the thread as well as and hence stops it yesteryear using stop() method inwards our Game shape which extends Runnable. When T1 starts it goes into a game loop as well as and hence pauses for 200 milliseconds. In betwixt nosotros receive got also seat the original thread to slumber yesteryear using TimeUnit.sleep() method. So original thread tin hold off for merely about fourth dimension as well as inwards the meantime, T1 volition resume as well as finished. If you lot receive got non read already as well as hence you lot must read Java Concurrency inwards Practice to arrive at a comprehensive agreement of multithreading inwards Java.




In 1 example, nosotros receive got learned 2 ways to interruption a thread inwards Java, yesteryear using Thread.sleep() method as well as TimeUnit.sleep() method. The declaration you lot overstep to sleep() is fourth dimension to slumber inwards a millisecond but that's non clear from code. This is where TimeUnit shape 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 run across its much to a greater extent than clear how long a thread volition hold off now. In short, utilisation TimeUnit class' sleep() method to interruption a thread because it's to a greater extent than readable. To larn to a greater extent than nigh TimeUnit class, run across my postal service why to prefer TimeUnit inwards Java.


Thread.sleep() as well as TimeUnit Example

import static java.lang.Thread.currentThread;  import java.util.concurrent.TimeUnit;  /**  * Java Program to demonstrate how to interruption a thread inwards Java.  * There is no interruption method, but in that location are multiple agency to interruption  * a thread for brusk menses of time. Two pop agency is either  * yesteryear 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 off to run across 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 directly going to pause");                          try {                 Thread.sleep(200);             } catch (InterruptedException e) {                                e.printStackTrace();             }                          System.out.println("Game thread is directly resumed ..");         }                  System.out.println("Game thread is stopped....");     }          public void stop(){         isStopped = true;     } }  Output original is stopping game thread Game thread is running..... Game thread is directly going to interruption Game thread is directly resumed .. Game thread is stopped.... original is finished directly 


Important points nigh sleep() method :

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

 There are multiple ways to interruption or halt the execution of currently running thread How to interruption Thread inwards Java using Sleep() as well as TimeUnit Example


1) Thread.sleep() is a static method as well as it ever puts the electrical current thread to sleep.

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

3) The slumber method doesn't guarantee that the thread volition slumber for just that many milliseconds, its accuracy depends on upon arrangement timers as well as it's possible for a thread to woke before.

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


That's all nigh how to seat a thread on interruption yesteryear using Thread.sleep() method as well as TimeUnit's sleep() method. It's improve to utilisation TimeUnit shape because it improves readability of code, but its also non hard to retrieve that declaration passed to sleep() method is inwards millisecond. Two fundamental things to retrieve is that Thread.sleep() is a static method as well as ever put the electrical current thread to sleep, as well as it doesn't loose whatever lock held yesteryear sleeping thread.

Further Learning
Java Fundamentals Part 1,2
Java Concurrency inwards Practice
Applying Concurrency as well as Multi-threading to Common Java Patterns

If you lot similar this tutorial as well as interested inwards learning to a greater extent than nigh multi-threading inwards Java. You tin also receive got a expect at next Java multi-threading tutorials :
  • 10 things every Java programmer should know nigh Thread shape (article)
  • What is the divergence betwixt Thread as well as Runnable inwards Java? (answer)
  • What is the divergence betwixt Process as well as Thread inwards Java? (answer)
  • Understanding the divergence betwixt wait() as well as sleep() inwards Thread? (answer)
  • What is the divergence betwixt Callable as well as Runnable inwards Java? (answer)
  • What is the divergence betwixt wait() as well as yield() method inwards Java? (answer)
  • When to utilisation notify() as well as notifyAll() inwards Java? (answer)
  • What is the divergence betwixt CyclicBarrier as well as CountDownLatch inwards Java? (answer)
  • The divergence betwixt yield() as well as sleep() method inwards Java? (answer)

Thanks for reading this article, if you lot similar this tutorial as well as hence delight percentage amongst your friends as well as colleagues.

Subscribe to receive free email updates:

0 Response to "How to interruption Thread inwards Java using Sleep() as well as TimeUnit Example"

Posting Komentar