码迷,mamicode.com
首页 > 其他好文 > 详细

interrupt, isInterrupted, interrupted

时间:2016-04-01 01:12:18      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

interrupt, isInterrupted, interrupted

今天学习了java多线程中的终止线程的相关知识, 稍微了解了下用法, 这里记录一下.

1.interrupt

通常情况, 我们不应该使用stop方法来终止线程, 而应该使用interrupt方法来终止线程. 看代码:

package com.bao.bao;


/**
 * Created by xinfengyao on 16-3-29.
 */
public class ThreadDemo1 extends Thread {
    boolean stop = false;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new ThreadDemo1(), "my thread");
        System.out.println("starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("interrupting thread...");
        thread.interrupt();
        System.out.println("线程是否中断:" + thread.isInterrupted());
        Thread.sleep(3000);
        System.out.println("stopping application");
    }
    @Override
    public void run() {
        while (!stop) {
            System.out.println("my thread is running...");
            long time = System.currentTimeMillis();
            while (System.currentTimeMillis() - time < 1000) {}
        }
        System.out.println("my thread exiting under request...");
    }
}

运行结果:

starting thread...
my thread is running...
my thread is running...
my thread is running...
interrupting thread...
线程是否中断:true
my thread is running...
my thread is running...
my thread is running...
stopping application
my thread is running...
my thread is running...
my thread is running...
my thread is running...
........

咦? 运行结果明明看到了线程是已经中断了的, 为什么还是一直在运行呢? 难道interrupt()方法有问题? 下面是我看别人博客了解到的知识:

实际上, 在java api文档中对该方法进行了详细的说明. interrupt方法并没有实际中断线程的执行, 只是设置了一个中断状态, 当该线程由于下列原因而受阻时, 这个中断状态就起作用了.

(1)如果线程在调用了Object类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long,

int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个InterruptedException异常。这个时候,我们可以通过捕获 InterruptedException异常来

终止线程的执行,具体可以通过return等退出或改变共享变量的值使其退出.

(2)如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个

ClosedByInterruptException。这时候处理方法一样,只是捕获的异常不一样而已。

 

interrupt, isInterrupted, interrupted

标签:

原文地址:http://www.cnblogs.com/NewMan13/p/5343423.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!