java Thread类的stop,interrupt,isinterrupt 方法概述以及区别

 Thread类正确终止进程的方法应该用 interrupt()方法,而不应该直接使用stop方法

interrupt() 方法是对线程发起一个中断信号,但并不是真正的终止一个线程,该方法是给线程标志一个线程中断位,不代表立刻中断,该线程也可以不予理财,所以在JAVA当中线程是协作式的,而不是抢占式

 isinterrupted() 判断当前线程是否被终断(常用)

 interrupted()     也是判断线程是否被终端,但他会修改中断标识位为TRUE

假如你的代码没有继承Thread类而是实现了Runable接口,则用Thread.currentThread().isinterrupted()方法来判断

例子:


package test;

public class NewThread {

    private static class UseThread extends Thread{
        public UseThread(String name){
            super(name);
        }
        
        public void run (){
            String threadName = Thread.currentThread().getName();
            System.out.println( threadName +"interrupt flag ="+isInterrupted());
            while(!isInterrupted()){
                System.out.println(threadName+"is running");
                System.out.println(threadName+"inner interrupt flag ="+isInterrupted());
            }
            System.out.println(threadName+" interrupt flag ="+isInterrupted());
        } 
    }

    public static void main(String[] args) throws InterruptedException {
        Thread endThread = new UseThread("endThread");
        endThread.start();
        Thread.sleep(20);
        endThread.interrupt();   //中断线程,其实是设置一个线程的中断标识位
    }
}
 

猜你喜欢

转载自blog.csdn.net/dzh145/article/details/89515743