Methods for stopping thread execution in Java

Source: Internet
Author: User

Methods for stopping thread execution in Java
Methods for stopping thread execution in Java
I. Theory of suspending or stopping a thread

In Java programming, there are several methods to pause or stop the currently running thread. Thread. Sleep () is the most correct method for transferring a Thread to sleep. Some may ask why wait for wait () or notify ()? You must know that waiting or notification is not a good method.
The thread can be blocked by waiting for wait (). This is a method of conditional waiting. When the condition is met, the thread changes from blocking to waiting. Although a timeout setting can be placed while waiting for the wait () condition, the purpose of waiting for wait () is not the same, and waiting for wait () is designed for Java thread communication.
The sleep () method allows the thread to sleep at the specified time from the current start. Do not use sleep () instead of waiting for wait () or notifying notify (), or vice versa.
Example of Java thread communication: http://javarevisited.blogspot.sg/2013/12/inter-thread-communication-in-java-wait-notify-example.html
Waiting for wait () or notifying notify () should not be used to pause the thread. Another reason is that waiting for wait () or notifying notify () requires a lock. They can only be called from a synchronous method or a synchronized code block. The overhead of obtaining and Releasing locks is relatively large. In addition, the lock mechanism is not required if the thread is paused.
Sleep () is different from wait (). sleep () transfers the current thread to the waiting state and does not release any lock it holds () when the thread is transferred to the blocking status, the lock held by the thread will be released.
In short, Java multi-threaded programming is not simple. Even simple tasks, such as creating a thread, stopping a thread, or pausing a thread, must master Java APIs carefully.

Ii. practice of suspending or stopping a thread

In the following example, to pause a Thread, you can use the Thread. sleep () or TimeUnit. sleep () method. In this example, there are two threads, the main thread is started by JVM, And it executes the main () method. The second thread is T1, which is created by the main thread to run the game cyclically. The Runnable task we passed is an infinite loop that will run until we stop it. Note that I use the volatile keyword.
The main thread first starts thread T1 and then stops the thread using the stop () method.
In this example, we have two methods to stop the running of a Thread: Thread. sleep () or TimeUnit. sleep. The TimeUnit class can specify the second (TimeUnit. SECONDS) and the millisecond (TimeUnit. MILLISECONDS. In general, using the sleep () method of TimeUnit makes the code easier to read.

 
 
  1. Import static java. lang. Thread. currentThread;
  2. Import java. util. concurrent. TimeUnit;
  3. Public class ThreadPauseDemo {
  4. Public static void main (String args []) throws InterruptedException {
  5. Game game = new Game ();
  6. Thread t1 = new Thread (game, "T1 ");
  7. T1.start ();
  8. // Stop the Game thread now
  9. System. out. println (currentThread (). getName () + "is stopping game thread ");
  10. Game. stop ();
  11. // View the stopped status of the Game thread
  12. TimeUnit. MILLISECONDS. sleep (200 );
  13. System. out. println (currentThread (). getName () + "is finished now ");
  14. }
  15. }

 
 
  1. class Game implements Runnable{
  2. private volatile boolean isStopped = false;
  3. public void run(){
  4. while(!isStopped){
  5. System.out.println("Game thread is running......");
  6. System.out.println("Game thread is now going to pause");
  7. try{
  8. Thread.sleep(200);
  9. } catch(InterruptedException e){
  10. e.printStackTrace();
  11. }
  12. System.out.println("Game thread is now resumed......");
  13. }
  14. System.out.println("Game thread is stopped......");
  15. }
  16. public void stop(){
  17. isStopped = true;
  18. }
  19. }

The program output is as follows:
Game thread is running ......
Main is stopping game thread
Game thread is now going to pause
Game thread is now resumed ......
Game thread is stopped ......
Main is finished now

Note:
Volatile Keyword: When a shared variable is modified by volatile, it ensures that the modified value is immediately updated to the primary storage. When other threads need to read this value, it reads the new value from the primary memory. The volatile keyword ensures visibility. The visibility of common shared variables cannot be guaranteed, because after the common shared variables are modified, it is not clear when they are written to the primary storage. When other threads read the shared variables, in this case, the memory may still be the old value, so visibility cannot be guaranteed.
Synchronized and Lock can also ensure visibility. synchronized and Lock can ensure that only one thread obtains the Lock at the same time and then executes the synchronization code, before the lock is released, the modification to the variable is refreshed to the primary storage. This ensures visibility.
After being modified by volatile, a shared variable (the member variable of the class and the static member variable of the class) has two meanings:
1. ensure the visibility of different threads when operating on this variable, that is, a thread modifies the value of a variable, which is immediately visible to other threads.
2. disable command re-sorting.
The volatile keyword disables Command Re-sorting. It has two meanings:
1. when the program executes the read or write operations on the volatile variable, all the changes in the previous operations must have been completed, and the results are visible to subsequent operations; the subsequent operations are certainly not performed.
2. During command optimization, statements that access the volatile variable cannot be placed behind them and the statements that follow the volatile variable cannot be placed before them for execution.
Volatile generally cannot replace sychronized, because volatile cannot guarantee the atomicity of operations. Even if it is just I ++, it is actually composed of multiple atomic operations: read I; inc; write I, if multiple threads execute I ++ at the same time, volatile can only ensure that the I they operate on is the same memory, but dirty data may still be written.

Iii. Summary of sleep () method

The Thread. sleep () method can pause or stop a Thread. Note the following details:
1. The Thread. sleep () method is a static method, which always transfers the current Thread to sleep.
2. You can call the interrupt () method to wake up the current sleeping thread.
3. The sleep () method does not guarantee that the thread can be accurately transferred to sleep within the specified millisecond. Its accuracy depends on the system timer.
4. It will not release the lock it acquires.

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.