并发编程之线程中断

在java中,线程中断是一种重要的线程写作机制,从表面上理解,中断就是让目标线程停止执行的意思,实际上并非完全如此。在上面中,我们已经详细讨论了stop方法停止线程的坏处,jdk中提供了更好的中断线程的方法。严格的说,线程中断并不会使线程立即退出,而是给线程发送一个通知,告知目标线程,有人希望你退出了!至于目标线程接收到通知之后如何处理,则完全由目标线程自己决定,这点很重要。

Thread提供了3个与线程中断有关的方法

(1)public void interrupt() //中断线程,设置中断标志位为true

(2)public boolean isInterrupted() //判断线程是否被中断

(3)public static boolean interrupted() //判断线程是否被中断,并清除当前中断状态

1、interrupt中断线程

class ThreadTest extends Thread{
    @Override
    public void run() {
        while (true){
            if(this.isInterrupted()){
                System.out.println("线程即将退出");
                break;
            }
        }
    }
}
public static void main(String[] args) throws Exception{
    ThreadTest threadTest=new ThreadTest();
    threadTest.setName("threadTest");
    threadTest.start();
    TimeUnit.SECONDS.sleep(2);
    threadTest.interrupt();
}

interrupt()方法被调用之后,线程的中断标志将被置为true,循环体中通过检查线程的中断标志是否为ture,如果为true即退出循环。

2、变量法中断线程

class ThreadTest extends Thread{
    protected volatile boolean isStop=false;
    @Override
    public void run() {
        while (true){
            if(isStop){
                System.out.println("线程即将退出");
                break;
            }
        }
    }
}
public static void main(String[] args) throws Exception{
    ThreadTest threadTest=new ThreadTest();
    threadTest.setName("threadTest");
    threadTest.start();
    TimeUnit.SECONDS.sleep(2);
    threadTest.isStop=true;
}

注意:如果一个线程调用了sleep方法,一直处于休眠状态,只能用线程提供的interrupt方法来中断线程。

3、当线程调用了sleep方法后,中断线程

public static void main(String[] args) throws Exception{
    Thread threadTest=new Thread(){
        @Override
        public void run() {
            while (true){
                try{
                    TimeUnit.SECONDS.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                    //注意:sleep方法由于中断而抛出异常之后,线程的中断标志会被清除(置为false),所以在异常中需要执行this.interrupt()方法,将中断标志位置为true
                    this.interrupt();
                }
                if(this.isInterrupted()){
                    System.out.println("线程即将退出");
                    break;
                }
            }
        }
    };
    threadTest.setName("threadTest");
    threadTest.start();
    TimeUnit.SECONDS.sleep(2);
    threadTest.interrupt();
}
发布了69 篇原创文章 · 获赞 2 · 访问量 4162

猜你喜欢

转载自blog.csdn.net/zuodaoyong/article/details/104219641
今日推荐