美文网首页
Thread中断

Thread中断

作者: 叫我C30混凝土 | 来源:发表于2020-09-29 23:17 被阅读0次
    • 为什么他们都抛出InterruptedException?
      Thread.sleep();
      BlockingQueue.put()/take();
    • Thread.interrupt()唯一的作用就是取消一个耗时的操作;
    // newThread 在sleep到500ms时,被主线程中断;
    public static void main(String[] args) throws InterruptedException {
            Thread newThread = new Thread(()->{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("I'm interrupted!");
                    e.printStackTrace();
                }
            });
            newThread.start();
    
            Thread.sleep(500);
            newThread.interrupt();
        }
    
    控制台结果:
    java.lang.InterruptedException: sleep interrupted
        at java.lang.Thread.sleep(Native Method)
        at com.jd.paas.ofc.fpe.transfer.core.domain.support.model.ware.ProductExtInfo.lambda$main$0(ProductExtInfo.java:23)
        at java.lang.Thread.run(Thread.java:748)
    I'm interrupted!
    
      1. 任何线程都可以被中断吗? --不是,取决于这个线程自己的决定;
    
    // 例子: newThread 无限循环,不会被打断
    public static void main(String[] args) throws InterruptedException {
            Thread newThread = new Thread(()->{
                try {
                    int i = 0;
                    while (true){
                        doNothing();
                        i++;
                    }
                } catch (InterruptedException e) {
                    System.out.println("I'm interrupted!");
                    e.printStackTrace();
                }
            });
            newThread.start();
    
            Thread.sleep(500);
            newThread.interrupt();
        }
    
        private static void doNothing() throws InterruptedException{
        }
    
      2. 中断只能发生在这些方法里吗? -- 取决于线程自己的策略,JVM的阻塞方法都会正常响应;
    
    • 允许线程A对线程B进行有限程度的控制;
      1.线程可以选择不响应InterruptedException,但是不推荐;
      2.除非你非常确定目标线程的中断特性,否则不要中断他;
        public static void main(String[] args) throws InterruptedException {
            Thread newThread = new Thread(()->{
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // 如果无法处理InterruptedException中断,那么最好重新设置中断标志位,使得其他人能知道该线程被中断了;
                    Thread.currentThread().interrupt();
                }
            });
            newThread.start();
        }
    

    常见的线程取消方法:
    1. 线程池ExecutorService的Future中存在cancel(boolean mayInterruptIfRunning);
    @param mayInterruptIfRunning {@code true} if the thread executing this task should be interrupted; otherwise, in-progress tasks are allowed to complete //如果入参mayInterruptIfRunning 是true,那么正在运行的线程中断,否则允许正在进行的线程完成后,才被取消;

    相关文章

      网友评论

          本文标题:Thread中断

          本文链接:https://www.haomeiwen.com/subject/vwjyuktx.html