线程终止,中断

线程中断有两种方式
1、interrrupt stop
interrupt 标记当前线程的状态为中断,stop粗暴强制中断当前线程。

Thread thread = new Thread();
        thread.stop();
        thread.interrupt();

首先看看interrupt中断线程比如:


public class ThreadInterrupt extends Thread{

    public static void main(String[] args) throws InterruptedException {
        ThreadInterrupt threadInterrupt = new ThreadInterrupt();
        threadInterrupt.start();
        sleep(300);
        threadInterrupt.interrupt();
    }

    @Override
    public void run() {
        for (int i = 0; i < 200000; i++) {
            System.out.println("输出为:"+(i+1))
        }
    }
}

interrupt 中断线程是把线程标记为中断,后续处理交给线程自己,他会循环所有。
输出为:199995
输出为:199996
输出为:199997
输出为:199998
输出为:199999
输出为:200000

Thread thread = new Thread();
        thread.stop();
        thread.interrupt();

再看看stop() 来中断线程比如:


public class ThreadInterrupt extends Thread{

    public static void main(String[] args) throws InterruptedException {
        ThreadInterrupt threadInterrupt = new ThreadInterrupt();
        threadInterrupt.start();
        sleep(300);
        threadInterrupt.stop();
    }

    @Override
    public void run() {
        for (int i = 0; i < 200000; i++) {
            System.out.println("输出为:"+(i+1))
        }
    }
}

sopt 中断线程是直接终止线程内的所有逻辑,全部停止。
输出为:53210
输出为:53211
输出为:53212
输出为:53213
输出为:53214

2、中断状态标记,首先解释三个名词
interrupt 中断当前线程
isInterrupted 判断当前线程状态是否被中断 true:已经被中断, false: 未被中断。
interrupted 判断当前线程是否被中断 true:已被中断, false:未被中断;并且清楚中断标记。

public class ThreadInterrupt extends Thread{

    public static void main(String[] args) throws InterruptedException {
        ThreadInterrupt threadInterrupt = new ThreadInterrupt();
        threadInterrupt.start();
        sleep(300);
        threadInterrupt.interrupt();
    }

    @Override
    public void run() {
        for (int i = 0; i < 60000; i++) {
            System.out.println("输出为:"+(i+1));
            // 判断当前线程是否中断
            if (ThreadInterrupt.currentThread().isInterrupted()) {
                System.out.println("线程已经中断。");
                // interrrupted 判断当前线程是否中断 并且清楚中断标记。
                if (Thread.interrupted()) {
                    System.out.println("二次判断线程已中断。");
                }
            }
            if (!Thread.currentThread().isInterrupted()) {
                System.out.println("第二次被唤起线程");
            }
        }
    }
}

你可能感兴趣的:(线程终止,中断)