Java review --- thread stop

stop()

The stop() method can indeed stop a running thread, but this method is unsafe, and this method has been deprecated, it is best not to use it.

Why stop is deprecated:

  1. Calling the stop() method will immediately stop all the remaining work in the run() method, including the catch or finally statement, and throw a ThreadDeath exception (usually this exception does not need to be explicitly caught), so it may cause some The clean-up work cannot be completed, such as the closing of files, databases, etc.
  2. Calling the stop() method will immediately release all the locks held by the thread, resulting in data not being synchronized and data inconsistency problems.

interrupt()

stop() is not safe, we need to use the interrupt() method if we want to interrupt the thread.

But this method does not stop the loop directly like using break in the for loop, but just marks a stop in the current thread, not really stopping the thread.

In other words, thread interruption does not immediately terminate the thread, but informs the target thread that someone wants you to terminate. As for what the target thread will do after receiving the notification, it is entirely up to the target thread to decide on its own. This is very important. If the thread exits unconditionally immediately after interruption, then we will encounter the old problem of the stop() method again.

public class InterruptThread1 extends Thread{
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            InterruptThread1 t = new InterruptThread1();
            t.start();
            Thread.sleep(200);
            t.interrupt();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
		@Override
		public void run() {
    
    
		    super.run();
		    for(int i = 0; i <= 200000; i++) {
    
    
		        //判断是否被中断
		        if(Thread.currentThread().isInterrupted()){
    
    
		            //处理中断逻辑
		            break;
		        }
		        System.out.println("i=" + i);
		    }
		}
}

Guess you like

Origin blog.csdn.net/why1092576787/article/details/114702936