一分钟读懂Java的线程中断

平时编程过程中你是否有以下疑问:

  • Thread.interrupt()能中断哪些阻塞?不能中断哪种阻塞?
  • 对于不能中断的那些阻塞,如果需要中断,该怎么做?

上代码

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {

        Scanner reader = new Scanner(System.in);
        try{
            System.out.println("开始执行了...");
            Thread t = Thread.currentThread();
            t.interrupt();
            System.out.println("调用了中断函数。");
            System.out.println("还不知道被中断了...");
            System.out.println("等待输入...");
            if(t.isInterrupted()){ //区别于t.Interrupted()
                System.out.println("发现被中断了,但我不管,继续执行...");
            }
            String input = reader.nextLine();
            System.out.println("你输入了:" + input);
            System.out.println("我累了,想睡一会儿");
            Thread.sleep(2000);
            System.out.println("睡了2s");
        }catch(InterruptedException e){
            System.out.println("发现已经被中断了。即将结束程序...");
            reader.close();
        }
    }
}
发布了36 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Cmainlove/article/details/53129973