中断机制之通过interrupt实现线程中断停止

如何停止中断运行中的线程?

首先,一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,自己来决定自己的命运,所以,Thread.stop,Thread.suspend,Thread.resume都已经被废弃了

interrupt实现线程中断停止

用isInterrupted 判断当前线程是否被中断 ,用interrupt()设置线程中断状态

package com.kwfruit.thread.interruptdemo;

import java.util.concurrent.TimeUnit;

public class Interruptdemo {


    static volatile boolean isStop = false;

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {

            while (true) {

                /**
                 * public boolean isInterrupted()
                 * 实例方法
                 * 判断当前线程是否被中断(通过检查中断标志位)
                 */
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true 程序停止");
                    break;
                }

                System.out.println("t1 --------hello interrupt api");

            }


        }, "t1");

        t1.start();

        System.out.println("t1 的默认中断标志为 "+t1.isInterrupted());


        try {
            TimeUnit.MICROSECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{

        /**
         * public void interrupt()
         * 实例方法 Just to set the interrupt flag
         * 实例方法仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程
         */
         t1.interrupt();


        },"t2").start();



    }

}

t1 的默认中断标志为 false
t1 --------hello interrupt api
t1 --------hello interrupt api
t1 --------hello interrupt api
t1 --------hello interrupt api
t1	 isStop被修改为true 程序停止

Process finished with exit code 0


posted @ 2024-01-21 15:50  KwFruit  阅读(4)  评论(0编辑  收藏  举报