zoukankan      html  css  js  c++  java
  • Thread interrupted() 线程的中断

    问题:

      1、线程的中断方式。

      2、为什么中断阻塞中的线程,会抛出异常。

    代码示例:  

    package com.hdwl.netty;
    
    public class ThreadInterrupted {
    
      public static void main(String[] args) {
    //    testNoInterrupted();
    //    testInterrupted();
        testInterruptedWithBlock();
      }
    
      //测试阻塞线程的中断
      private static void testInterruptedWithBlock() {
        MyInterruptedBlockThread mibt = new MyInterruptedBlockThread();
        mibt.start();
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        mibt.interrupt();//设置中断标示
      }
    
      //线程非阻塞中断的演示
      private static void testInterrupted() {
        MyInterruptedNoBlockThread mibt = new MyInterruptedNoBlockThread();
        mibt.start();
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        mibt.interrupt();//设置线程中断标示
      }
    
      //不中断线程的演示,由于未设置中断标示,所有线程永远不会中断。
      private static void testNoInterrupted() {
        MyInterruptedNoBlockThread mibt = new MyInterruptedNoBlockThread();
        mibt.start();
      }
    
    }
    //阻塞线程
    class MyInterruptedBlockThread extends Thread{
      @Override
      public void run() {
        //如果线程中断位置为true,则结束while循环
        while (!isInterrupted()){
          System.out.println("running……");
          try {
            sleep(2000);
          } catch (InterruptedException e) {
            e.printStackTrace();
            //当阻塞中的线程被中断,线程的中断标示被重置,所以需要重新设置
            interrupt();
          }
        }
        System.out.println("线程结束!");
      }
    }
    //非阻塞线程
    class MyInterruptedNoBlockThread extends Thread{
      @Override
      public void run() {
        //如果线程中断位置为true,则结束while循环
        while (!isInterrupted()){
          System.out.println("running……");
        }
        System.out.println("线程结束!");
      }
    }
    

    解答问题:

      1、线程的中断,使用设置中断标示的方式进行。

      2、中断阻塞中的线程抛出异常,是为了不让线程无休止的中断。因为设置中断标示,线程并不会马上停止,还需要等待下一次的CPU时间片到来,才能根据interrupted方法的返回值来终止线程。如果某个阻塞线程B,依赖于线程A的notify(或者其它操作,才能唤醒线程B),那么将线程A,B同时设置为中断标示,此时线程A已经死亡了,而线程B还一直等到唤醒,才能根据interrupted方法,进行线程的中断操作。因此,中断阻塞中的线程,必须抛出异常,方便我们进行后续的处理。

       

  • 相关阅读:
    Java的内存区域划分
    Java中的浮点型进行四则运算精度丢失的问题
    单例模式的几种写法
    如何掌握一门工具及对工具的认识
    记一个命运多舛的项目总结
    几个超级好用但很少有人知道的 webstorm技巧
    如何自定义中间件,实现业务代码无侵入监控及拦截
    如何减少和处理死锁
    快照读与加锁读
    谈谈Java常用类库中的设计模式
  • 原文地址:https://www.cnblogs.com/chen--biao/p/11358405.html
Copyright © 2011-2022 走看看