其他分享
首页 > 其他分享> > 面试官:来,聊一聊如何中断线程?

面试官:来,聊一聊如何中断线程?

作者:互联网

中断相关三个方法

聊一下如何中断线程?

中断处理与中断传播

public class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        try{
            for (int i = 0; i < 500000; i++) {
                if (this.interrupted()) {
                    System.out.println("should be stopped and exit");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
            System.out.println("this line cannot be executed. cause thread throws exception");
        }catch(InterruptedException e){
            /**这样处理不好
             * System.out.println("catch interrupted exception");
             * e.printStackTrace();
             */
             Thread.currentThread().interrupt();//这样处理比较好
        }
    }
}

Sleep与中断

private static void test3() throws InterruptedException {
	Thread thread = new Thread(() -> {
		while (true) {
			// 响应中断
			if (Thread.currentThread().isInterrupted()) {
				System.out.println("Java技术栈线程被中断,程序退出。");
				return;
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				System.out.println("Java技术栈线程休眠被中断,程序退出。");
			}
		}
	});
	thread.start();
	Thread.sleep(2000);
	thread.interrupt();
}

该示例会中断失败,因为sleep会清除中断标记。

private static void test4() throws InterruptedException {
	Thread thread = new Thread(() -> {
		while (true) {
			// 响应中断
			if (Thread.currentThread().isInterrupted()) {
				System.out.println("Java技术栈线程被中断,程序退出。");
				return;
			}

			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				System.out.println("Java技术栈线程休眠被中断,程序退出。");
				Thread.currentThread().interrupt();
			}
		}
	});
	thread.start();
	Thread.sleep(2000);
	thread.interrupt();
}

对比该代码,解决方案就是传播中断。

参考

1、https://www.cnblogs.com/hapjin/p/5450779.html

2、https://zhuanlan.zhihu.com/p/149205707

3、https://www.cnblogs.com/wulianshang/p/5801902.html/

标签:面试官,Thread,中断,System,聊一聊,线程,println,isInterrupted
来源: https://blog.csdn.net/u011877621/article/details/121421013