public class InterruptThread2 extends Thread{

    public static void main(String[] args) {
        try {
            InterruptThread2 t = new InterruptThread2();
            t.start();
            Thread.sleep(1000);
            t.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        super.run();
        for(int i = 0; i <= 800000; i++) {//设置中断标识,线程没有影响,还会继续运行。线程只有在方法执行完了,才会退出,
            System.out.println("i=" + i);
        }
    }
    
    public void run1() {
        super.run();
        for(int i = 0; i <= 200000; i++) {
            //判断是否被中断
            if(Thread.currentThread().isInterrupted()){
                //设置中断标识,线程没有影响,还会继续运行。这里要线程的方法执行完,线程就退出了。
                //处理中断逻辑
                for(int j = 0;j < 10 ;j++) {
                    System.out.println("sssss" + j);
                }
                break;
            }
            System.out.println("i=" + i);
        }
    }
}
public class InterruptThread1 extends Thread{

    public static void main(String[] args) {
        try {
            InterruptThread1 t = new InterruptThread1();
            t.start();
            Thread.sleep(1000);
            t.stop();//停止不了线程
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        super.run();
        for(int i = 0; i <= 800000; i++) {//设置中断标识,线程没有影响,还会继续运行。线程只有在方法执行完了,才会退出,
            try {
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("i=" + i);
        }
    }
}

 

相关文章:

  • 2021-11-28
  • 2021-12-05
  • 2021-12-06
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-04-13
猜你喜欢
  • 2021-10-11
  • 2022-12-23
  • 2020-03-01
  • 2018-11-28
  • 2021-05-20
  • 2021-07-22
相关资源
相似解决方案