Several ways to stop multithreading (explained in detail)

method one

Use the exit flag to make the thread exit normally, that is, the process terminates when the run method is completed.

public class TestFlagStop implements Runnable{
    
    

	//1、设置一个标示位
	private boolean flag = true;
	
	@Override
	public void run() {
    
    
		int i = 0;
		while(flag) {
    
    
			System.out.println("run...Thread"+i++);
		}
	}
	
	//2、设置一个公共的方法停止线程,转换标志位
	public void stop() {
    
    
		this.flag = false;
	}

	public static void main(String[] args) {
    
    
		TestFlagStop testStop = new TestFlagStop();
		new Thread(testStop).start();
		
		for (int i = 0; i < 1000; i++) {
    
    
			System.out.println("main"+i);
			if(i==900) {
    
    
				//调用stop方法切换标志位,让线程停止
				testStop.stop();
				System.out.println("线程该停止了");
			}
		}
	}
}

Way two

To stop a thread, the Thread.stop() method was used in the old JDK, but later it was found that this method is very dangerous and unsafe, because the stop() method has been marked as "obsolete/expired" in the JDK "" method, obviously it is functionally flawed. Just discard it here.

Way two

Use the interrupt method to interrupt the thread.

First, we use for-break with interrupt to stop the thread:

public class InterruptBreakStop extends Thread {
    
    
	@Override
    public void run() {
    
    
        for (int i = 0; i < 500000; i++) {
    
    
            if (this.isInterrupted()) {
    
    
                System.out.println("已经是停止状态了!我要退出了!");
                break;
            }
            System.out.println("i=" + (i + 1));
        }
        System.out.println("我被输出,如果此代码是for又继续运行,线程并未停止!");
    }

    public static void main(String[] args) {
    
    
    	InterruptBreakStop thread = new InterruptBreakStop();
        thread.start();
        try {
    
    
            Thread.sleep(2000);
            thread.interrupt();
       
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

From here, you can find that break just jumps out of the for loop, and the code after the for loop will run as usual!
Insert picture description here
In order to solve this problem, you can use the return method to terminate the thread.

public class InterruptReturnStop extends Thread {
    
    
	 @Override
	    public void run() {
    
    
	        while (true) {
    
    
	            if (this.isInterrupted()) {
    
    
	                System.out.println("停止了!");
	                return;
	            }
	            System.out.println("time=" + System.currentTimeMillis());
	        }
	    }

	    public static void main(String[] args) throws InterruptedException {
    
    
	    	InterruptReturnStop thread=new InterruptReturnStop();
	        thread.start();
	        thread.sleep(2000);
	        thread.interrupt();
	    }
}

Output result: It is
Insert picture description here
generally recommended to throw an exception so that the thread stops can be spread.

public class InterruptExceptionStop extends Thread {
    
    
	@Override
    public void run() {
    
    
	 	try {
    
    
	 		while (true) {
    
    
	            if (this.isInterrupted()) {
    
    
	                System.out.println("停止了!");
	                throw new InterruptedException();
	            }
	            System.out.println("time=" + System.currentTimeMillis());
	        }
		} catch (InterruptedException e) {
    
    
			System.out.println( "抛异常了" );
			e.printStackTrace();
		}
    }

    public static void main(String[] args){
    
    
    	InterruptExceptionStop thread=new InterruptExceptionStop();
        thread.start();
        try {
    
    
			thread.sleep(2000);
			thread.interrupt();
		} catch (InterruptedException e) {
    
    
			System.out.println( "抛异常了呀" );
			e.printStackTrace();
		}
        
    }
}

Insert picture description here
Note :

If interrupt() is used to stop a thread in the sleep state, the catch statement will be entered and the stop state value will be cleared to make it false. It can be understood as a mutual exclusion relationship. Once this interrupt method is used, the thread cannot be put to sleep. Otherwise, this error will be reported.

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43888891/article/details/115291302