Methods for stopping thread execution in Java

Source: Internet
Author: User

The method of stopping thread execution in Java CHSZS, reprint need to indicate. Blog home: Http://blog.csdn.net/chszs The theory of pausing or stopping threads

In Java programming, there are several ways to pause or stop a thread that is currently running. Using Thread.Sleep () is the most correct way to put a thread into sleep state. Perhaps someone would ask, why not use wait Waiting () or notify Notify ()? You know, using a wait or a notification is not a good way.
Threads can be blocked by waiting for the wait () implementation, which is the way the conditional waits, and then goes from blocking to waiting when the condition is met. Although you can put a timeout setting in waiting for wait () conditions, waiting for wait () is not designed to be the case, and waiting for Wait () is designed to be used for communication between Java threads.

Instead, you can let the thread sleep at the specified time from the current start by using sleep sleeping () mode. Be careful not to use sleep sleeping () instead of waiting for wait () or notification notify (), or vice versa.
Waiting for Wait () or notification notify () should not be used to pause the thread, and there is a reason to wait for wait () or notification notify () to require a lock. They can only be called from a synchronized method or a synchronized block of code, and the overhead of acquiring locks and releasing locks is large. And, just pausing the thread without introducing a lock mechanism.
Sleep () is a bit different from wait (), and sleep () puts the current thread into a wait state, which does not release any locks it holds, and wait () causes the thread to go into a blocking state and release the lock it holds.
In summary, Java multithreaded programming is not simple, and even simple tasks such as creating threads, stopping threads, or suspending threads require careful mastery of the Java API.

Second, suspend or stop the actual combat of the thread

In the following example, to pause a thread, you can use the Thread.Sleep () or Timeunit.sleep () method. In the example, there are two threads, the main thread is started by the JVM, and it executes the main () method. The second thread is called T1, which is created by the main thread and used to loop the game. The runnable task we pass is an infinite loop that will run until we stop it. Watch out, I used the volatile keyword. The
main thread starts T1 threads first, and then stops the thread using the Stop () method.
In this example, there are two ways to stop a thread from running, using the Thread.Sleep () method or using the Timeunit.sleep () method. The Timeunit class can specify either seconds or timeunit.seconds, or milliseconds, or timeunit.milliseconds. In general, using the Timeunit sleep () method makes the code easier to read.

Import static Java.lang.thread.currentthread;import Java.util.concurrent.timeunit;public class threadpausedemo{        public static void Main (String args[]) throws Interruptedexception {Game game = new Game ();        thread T1 = new Thread (game, "T1");        T1.start ();        Now stop the game thread System.out.println (CurrentThread (). GetName () + "is stopping game thread");        Game.stop ();        View the status of the 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 () {!isstopped} {System.out.println ("Game thread is running ...");            System.out.println ("Game thread is now going to pause");            try{Thread.Sleep (200);            } catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Game Thread is now resUmed ... ");    } System.out.println ("Game thread is stopped ...");    } public void Stop () {isStopped = true; }}

The program output is as follows:

Game thread is running......main is stopping game threadGame thread is now going to pauseGame thread is now resumed......Game thread is stopped......main is finished now

Note:
Volatile keyword: When a shared variable is modified by volatile, it will ensure that the modified value is immediately updated to main memory, and when other threads need to read the value, it will go to read the new value in master. The volatile keyword guarantees visibility. Common shared variables do not guarantee visibility, because when a common shared variable is modified, it is indeterminate when it is written to main memory, and when other threads go to read it may still be the original old value, and therefore cannot guarantee visibility.
Visibility is ensured through synchronized and lock, and synchronized and lock ensure that only one thread acquires the lock at the same time and executes the synchronization code, and that changes to the variable are flushed to main memory before the lock is released. Visibility can therefore be guaranteed.
A shared variable (a member variable of a class, a static member variable of a class) is modified by volatile, then it has two levels of semantics:

    1. The visibility of this variable is ensured by a thread that modifies the value of a variable, which is immediately visible to other threads.
    2. command reordering is prohibited.

The volatile keyword prohibit command reordering has two layers of meaning:

    1. When a program executes a read or write operation to a volatile variable, the change in its preceding action must have been made, and the result is already visible to the subsequent operation, and the operation behind it must not have been performed.
    2. In the case of instruction optimization, you cannot put the statements that are accessed by volatile variables behind them, and you cannot put the statements that follow the volatile variable in front of them.
      Volatile is generally not a substitute for sychronized, because volatile does not guarantee the atomicity of the operation, even if only i++, is actually composed of multiple atomic operations: Read I; Inc; Write I, if multiple threads execute i++,volatile at the same time can only guarantee that I is the same piece of memory, but it is still possible to write dirty data.
Iii. Summary of the Sleep () method

The Thread.Sleep () method allows the thread to pause or stop, and it has some details to note:

    1. The Thread.Sleep () method is a static method that always allows the current thread to go to sleep.
    2. You can call the interrupt () method to wake the currently sleeping thread.
    3. The sleep () method does not guarantee that the thread can accurately sleep within the specified millisecond, and its accuracy depends on the system's timer.
    4. It does not release the locks it obtains.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Methods for stopping thread execution in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.