Last week wrote an article on the multithreading, actually is more partial basic point of the article, and also compares vernacular, for everybody can see to understand, and some common examples, can be a very good help everyone understand multithreaded, published after I went to a few large and CSDN reactions are both good, everyone said hope to be able to write more articles like this, I want to write more articles about threads, so I’m going to start with the basics of threads and write two or three articles a week so that you can read and absorb more in your spare time.


In addition, I hope you can come to an interactive praise after reading what, also let me have a little creative power, in addition to talk about your ideas what, I can write a better article, no more nonsense to say, we begin today’s knowledge points to learn!

What is a thread interrupt?

In our Java program, there is more than one thread of execution, and the Java program is not finished until all threads have finished.

To give you an official description: The Java program is finished when all non-daemon threads finish running, or when one of them calls the system.exit () method.


Application scenarios of thread interrupts

Let’s take an example, for example, we are now in the download a more than 500 M, we click start download, that this time is to open a thread to download our files, but this time our Internet connection is not very awesome, dozens of KB on this run, as a young man I was not able to, I don’t come down, In this case, our first action is to end the download operation, in fact, closer to the program, this time we need to interrupt the thread.


We write this next to download code, look at how to interrupt a thread, here I have the default you have mastered how to create a thread, we simulate download this program, the first to get the system time, and then enter the cycle time of acquisition system, we will interrupt threads, if more than 10 seconds is not continue to download, Download speed at 1M per second:

public void run() { int number = 0; Long start = system.currentTimemillis ();while (trueLong end = system.currentTimemillis (); Long interval = end-start; // If it takes more than 10 seconds, we end the downloadif(interval >= 10000) {// Interrupt thread interrupted(); System.err.println("It's too slow. I'm off.");
               return;
           } else if (number >= 500) {
               System.out.println("File download completed"); // Interrupt thread interrupted();return;
           }

           number++;
           System.out.println("Downloaded" + number + "M"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code


The way to interrupt a thread

The Thread class provides a method that interrupts a Thread. Let’s take a look at how this method interrupts a Thread:

public static boolean interrupted() {
       return currentThread().isInterrupted(true);
   }Copy the code


This method checks if the current thread is interrupted, returning true if interrupted and false if not interrupted

private native boolean isInterrupted(boolean ClearInterrupted);Copy the code


By looking at the source code we can find that the interrupt thread is called to check whether the thread is interrupted method, set the value to true. This will return true when you call a method that checks if the thread is interrupted.


Note that thread.interrupted () only changes the status of the current Thread to say that it has been interrupted, whereas for a Thread that is not blocked it changes the interrupted status, i.e

Thread.isinterrupted () returns true for threads in the uninterruptible blocking state, such as threads waiting on these functions, thread.sleep (), which throws InterruptedException after receiving an interrupt signal, The interrupt state is also set to true.


Causes of InterruptedException caused by thread sleep

In fact, we are also half-informed about this, so I will write a wrong example, we have a look, to make this problem thoroughly clear:

public void run() {

       int number = 0;

       while (true) {// Check if the thread is interruptedif (isInterrupted()) {

               System.err.println("It's too slow. I'm off.");
               return;
           } else if (number >= 500) {
               System.out.println("Download completed");
               return;
           }

           number++;
           System.out.println("Downloaded" + number + "M"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code


This is our main program, waiting 10 seconds to interrupt the thread

public static void main(String[] args) throws InterruptedException { Thread thread = new PrimeGenerator(); // Start the thread thread.start(); // Wait 10 seconds to interrupt the Thread thread.sleep (1000); // Interrupt thread thread.interrupt(); }Copy the code


InterruptedException (InterruptedException) is a routine program that does not look like it.

Thread.sleep() does not interrupt a running Thread. Thread.sleep() does not interrupt a running Thread. Sleep () does not interrupt a running Thread. Thread.interrupt() is called to interrupt the Thread, but the sleep in the run() method will continue to execute. It will not stop executing the following code because of the interruption. When it executes Thread.sleep(), it throws InterruptedException because the current Thread has been interrupted.

At this point, do you understand the cause of this anomaly? Two other causes cause a thread to throw InterruptedException. Improper use of wait() and JOIN () also causes the thread to throw an exception.




Two ways to see if a thread is interrupted

The Thread class has a method called interrupted() that checks if the current Thread has been interrupted, as well as isInterrupted() that checks if the current Thread has been interrupted.

The method that interrupts the thread essentially sets this property to true; isInterrupted() simply returns this value.

The difference between the two methods is that isInterrupted() does not change the value of the interrupted() attribute, but instead changes the value of the interrupted() attribute. This is why we prefer to use isInterrupted() if a thread has been interrupted.