Basic Java skills: thread interruption

Source: Internet
Author: User

Imagine this scenario: in a certain period of time, our application requires a sub-thread to run continuously in the background. This may be a download process, which is a listener to the socket on the server, it may also be a drawing calculation process. What should we do when we want to terminate the thread? Is setting a flag variable to control the exit loop? Or use thread. stop ()? Or set thread = null? Sometimes we need a standard approach to solve a type of problem. This article is original, if you need to reprint, please indicate reprint address: http://blog.csdn.net/carrey1989/article/details/11918303 we must first understand, thread termination conditions, there are three situations: 1. when the run method of the thread executes the last statement in the method body. 2. When the retutrn statement is executed. 3. When an exception is not captured in the method. In earlier versions of Java, there is also a stop method. Other threads can call it to terminate the thread, but this method has been abandoned, so those who are still using it should not continue to use it. The correct idea is to use the interrupt method to terminate our thread. First, understand what the interrupt method has done: Every thread has an interruption status, which is a boolean sign. When the thread calls the interrupt method, the interruption status will be set. If you want to check the interrupt status, you can use Thread. currentThread (). isInterrupted () to determine whether to interrupt. However, if the thread is congested (sleep or wait), an InterruptedException exception occurs when the interrupt method is called. This is what we can use. Similarly, if the interrupt state is first set to a bit, and then the sleep method is called, the thread will not sleep. On the contrary, the thread will clear the interrupt state and then throw InterruptedException. The call of interrupt does not mean that the thread will be terminated, whether the thread will be terminated, and how it will continue. It is controlled by the programmer. In this article, we will discuss the standard usage of terminating threads, and then apply them in an example. In this example, we simulate two scenarios: file copy and game drawing. As shown in figure. After you click start, the progress bar on the top shows the progress of file copying. Click end to stop copying. Click draw to draw all kinds of rectangles on the screen. Click stop to stop the painting. First, let's look at the background thread writing in two situations:

public void run(){    try{        ...        while(!Thread.currentThread.isInterrupted() && more work to do)        {            do more work        }    }    catch(InterruptedException)    {        //thread was interrupted during sleep or wait    }    finally    {        cleanup, if required    }    //exiting the run method terminates the thread}public void run(){    try{        ...        while( more work to do)        {            do more work            Thread.sleep(delay);        }    }    catch(InterruptedException)    {        //thread was interrupted during sleep or wait    }    finally    {        cleanup, if required    }    //exiting the run method terminates the thread}

 

The first method is applicable to background download, file copy, and similar situations, and the second method is suitable for game screen refresh or similar situations. The first method uses the interrupt method as the request to terminate, so that the loop jumps out and the run method is executed completely. The second method is to call interrupt when the thread is sleep. InterruptedException is thrown out of the loop and the thread execution ends. In fact, the difference between the two writing methods is that the second method uses sleep. In our example, the code corresponding to the two methods is as follows: This section implements file copy:
private class CopyRunnable implements Runnable {            @Override          public void run() {              File fromFile = new File(Environment.getExternalStorageDirectory()                      .getAbsolutePath() + "/abc.exe");              long fileLength = fromFile.length();              long copyedLength = 0;              File toFile = new File(Environment.getExternalStorageDirectory()                      .getAbsolutePath() + "/abc_.exe");              if (toFile.exists()) {                  toFile.delete();              }              try {                  FileInputStream fileInputStream = new FileInputStream(fromFile);                  FileOutputStream fileOutputStream = new FileOutputStream(                          toFile, true);                  byte[] buffer = new byte[2048];                  int readLength = 0;                  while (!Thread.currentThread().isInterrupted()                          && (readLength = fileInputStream.read(buffer)) != -1) {                      fileOutputStream.write(buffer, 0, buffer.length);                      copyedLength += readLength;                      int progress = (int) ((float) copyedLength / fileLength * 100);                      handler.obtainMessage(0, progress, 0).sendToTarget();                  }              } catch (FileNotFoundException e) {                  e.printStackTrace();              } catch (IOException e) {                  e.printStackTrace();              } finally {                  handler.obtainMessage(1).sendToTarget();              }          }        }  

 

This section implements rectangular plotting:
private class DrawRunnable implements Runnable {            @Override          public void run() {              try {                  while (true) {                      long beginTime = System.currentTimeMillis();                      paint.setColor(getColor());                      getCoor();                      postInvalidate();                      long endTime = System.currentTimeMillis();                      if (endTime - beginTime < 150) {                          Thread.sleep(150 - (endTime - beginTime));                      }                  }              } catch (InterruptedException e) {                  e.printStackTrace();              } finally {                }          }        }  

 

In fact, these two methods use the characteristics of the interrupt method to terminate the thread by throwing out the loop through thread interruption slots or exceptions. If you are interested in this code, you can download the code at the end of the article. The final method is summarized as follows: void interrupt () sends an interrupt request to the thread. The thread interruption status is set to true. If the thread is currently blocked by a sleep call, an InterruptedException exception is thrown. Static boolean interrupted () tests whether the current thread (that is, the thread executing this command) is interrupted. Note that this is a static method. This call produces side effects. It sets the interruption status of the current thread to false. Boolean isInterrupted () to test whether the thread is interrupted. Unlike static interrupt methods, this call does not change the thread interruption status. Static Thread currentThread () returns the Thread object representing the current execution Thread.

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.