Thread start and safe termination

1. Thread start

There are two ways to start a thread, namely inheriting the Thread class and rewriting the Runable interface, as follows:
insert image description here


1.1、Thread

Regarding the thread creation by Thread, the thread creation function in Java multithreading has already been introduced, so I won’t go into details here.


1.2、Runnable

There is actually no essential difference between Runnable and Thread, which is the difference between interface and class. Rewriting Runnbale still needs to start the thread through Thread.


In use, because Java does not allow multiple inheritance, Runnable can avoid the troubles caused by the limitation of single inheritance.


1.3、Callable

Since the Runnable interface has no return value, if a return value is required in some scenarios, then the Callable interface needs to be used.

public class App {
    
    
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }
}

class MyCallable implements Callable<String> {
    
    
    @Override
    public String call() throws Exception {
    
    
        return "success";
    }
}

It uses FutureTaskthe class to execute, and the FutureTask class implements the Future and Runnable interfaces at the same time, so it can be executed by threads as a Runnable, and can also be used as a Future to get the return value of Callable.
insert image description here

It should be noted that when obtaining the return value, FutureTask.get()a blocking method is used. Once this method is called, the subsequent code will be blocked, and the execution can only continue after the Callable method is executed.


Second, the suspension of the thread

Often there may be a need to stop a thread. suspend()There are , resume(), stop()and other methods in the API of Java , and their functions are to suspend the thread, resume the execution of the thread, and terminate the thread.
insert image description here

However, it is found that these three methods are no longer recommended, because the three methods perform immediate operations on our threads. For example, the methods stop()will suspend()immediately stop and suspend our threads, but the resources in the threads will not be released. It may cause a program deadlock problem.


2.1, interrupt() and isInterrupted() methods

A thread should not be interrupted or stopped forcibly by other threads, but should be stopped by the thread itself. So you can use interrupt()the method to notify the thread that it should be interrupted, but whether to interrupt or continue running should be handled by the notified thread itself.


Calling the interrupt() method will only set the thread's interrupt flag to true, not force an interruption. At the same time, Java also provides a method to query whether the thread is interrupted isInterrupted()and a static method Thread.interrupted(). The difference is that the static method will set the state to false after querying the interrupted state of our thread.
insert image description here

In the following tests, it can be found that the static method Thread.interrupted(), which queries whether the thread is interrupted, changes the interrupt flag to false. In addition, the main thread is directly used to view it here. If a new thread is created for testing , you need to start the thread first and keep it running, otherwise the query must be false
insert image description here


In addition, it is not recommended to customize a cancel flag to suspend the running of the thread. Because when there is blocking in the run() method, the custom cancellation flag cannot be detected, and the thread must return from the blocking call before checking the cancellation flag.


2.2, InterruptedException exception

If a thread is in a blocked state (for example, the thread calls thread.sleep(), thread.join(), thread.wait(), etc.), and the interrupt method is called to interrupt the operation, an InterruptedException will be thrown, but Immediately after an exception is thrown, the interrupt flag bit of the thread is cleared, that is, reset to false.
insert image description here


So we are in the InterruptedException exception, if we confirm that the thread needs to be interrupted, here we must set our interrupt flag again.
insert image description here


2.3、FutureTask

The FutureTask that implements the Future interface also provides us with other interrupt methods, such as cancel()can also send an interrupt signal.


In addition, the FutureTask class also provides isDone()and isCancelled(), which are used to judge whether the task is completed and whether the task is cancelled, respectively.
insert image description here

  • cancel(boolean): The task is canceled and returns true, otherwise false
    1. cancel(true): will interrupt the running task
    2. cancel(false): will not interrupt tasks that are already running
  • isDone(): Whether the task is completed, whether it ends normally, ends abnormally, or cancels itself, returns true
  • isCancelled(): Whether the task was canceled before completion

Guess you like

Origin blog.csdn.net/rockvine/article/details/124972509