preface

When we use sleep() to put a thread to sleep in Java, we always need to include it with a try catch:

        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
Copy the code

However, we rarely execute other code in a catch, as if the try catch is a given, but in fact, there is no reason to have an extra try catch.

Before I tell you why, I want to talk about another point, which is how to stop threads.

How to stop a thread

stop()

The most direct way to stop is to call stop(), which terminates the thread’s execution, as in:

Thread Thread = new Thread(){@override public void run() {while (true){Thread Thread = new Thread(){@override public void run() { System.out.println(System.currentTimeMillis()); }}}; thread.start(); // Stop the thread after two seconds of sleep try {sleep(2000); thread.stop(); } catch (InterruptedException e) { e.printStackTrace(); }Copy the code

Output result:

·· 1643730391073 1643730391073 1643730391073 1643730391073 Process Finished with exit code 0Copy the code

Obviously you can suspend the thread. However, the method is now marked abandoned.

It means:

This method is designed to stop the thread and raise the thread death exception, but it is not safe because it directly terminates the thread to free the lock, which is difficult to properly raise the thread death exception to handle, so it is better to set a judgment condition, This condition is then evaluated during thread execution to determine whether to stop the thread, which can be processed and exit the thread in an orderly manner. If a thread is waiting too long, it interrupts the thread and throws an exception.

As mentioned above, we can set a variable for control. Of course, we can declare a bool for determination, but a better way is to use interrupt().

interrupt()

Source:

public void interrupt() { if (this ! = Thread.currentThread()) checkAccess(); synchronized (blockerLock) { Interruptible b = blocker; if (b ! = null) { interrupt0(); // Just to set the interrupt flag b.interrupt(this); return; } } interrupt0(); }Copy the code

Just to set the interrupt flag, it does not interrupt the thread directly, so if we need to use interrupt(), we also need to determine the state of the interrupt in the thread:

Thread Thread = new Thread(){@override public void run() {while (true){Thread Thread = new Thread(){@override public void run() {while (true){ if(isInterrupted()){ return; } System.out.println(System.currentTimeMillis()); }}}; thread.start(); // Mark interrupt thread try {sleep(2000); thread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); }Copy the code

Output result:

·· 1643731839919 1643731839919 1643731839919 Process finished with exit code 0Copy the code

This will also interrupt the thread normally.

Ok, how to interrupt the thread is finished here, everyone bye ~~

A: hello! Sleep () = sleep() = sleep() = sleep()

It seems so.

Interrupt waiting

Let’s look again at the description where sleep() is marked abandoned:

 If the target thread waits for long periods (on a condition variable, for example),
 the interrupt method should be used to interrupt the wait.
Copy the code

That is, when a thread is waiting too long, interrupt() should interrupt the wait.

If the thread is sleeping (), the interrupt() method is invoked to interrupt the thread’s sleep state and throws InterruptedException.

Since interrupt() is called to terminate the thread as quickly as possible, there is no point in continuing to sleep. It should terminate as quickly as possible.

Thread Thread = new Thread(){@override public void run() {try {sleep(10000); } catch (InterruptedException e) {system.out.println (" Sleep status is interrupted!" ); e.printStackTrace(); }}}; thread.start(); // Mark interrupt thread try {sleep(2000); thread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); }Copy the code

Output result:

Sleep has been interrupted! java.lang.InterruptedException: sleep interrupted at java.base/java.lang.Thread.sleep(Native Method) at com.magic.vstyle.TestMain$1.run(TestMain.java:16) Process finished with exit code 0Copy the code

At this point, we can catch the exception and perform additional operations, such as recycling resources. At this point, stopping the thread is a controlled behavior.