[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备忘]Java线程的sleep方法被中断时,应该处理异常~~

上一篇:[转帖]Java动态载入Jar包中的类的一个小例子
下一篇:[整理]javax.comm串口操作的小实用类~~

添加日期:2011/11/16 16:59:44 快速返回   返回列表 阅读4351次


package thread;

public class ThreadInterruptTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Thread target = new countThead();
        target.start();

        try {
            Thread.sleep(10100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        target.interrupt();
    }

}

class countThead extends Thread {
    public void run() {
        int i = 0;
        while (!isInterrupted()) {
            System.out.println("running... " + i);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Interrupted... ");

                // sleep时,被中断,会自动清除当前进程的中断状态,所以isInterrupted()是false。
                System.out.println("isInterrupted()... " + isInterrupted());

                // 这时,要么进行处理,比如跳出while循环,要么重置中断状态。
                Thread.currentThread().interrupt();
            }

            i++;
            // 一般代码时被中断,isInterrupted()是true
            System.out.println("isInterrupted()... " + isInterrupted());
        }
        System.out.println("exit... ");
    }
}


如果上面的代码注释掉Thread.currentThread().interrupt();这行,
那么,假如正在sleep时,被中断了,sleep方法抛出InterruptedException异常,
被抓住,可是没有处理,结果就是循环还继续执行~~~~

有了这句,就没问题了,如下面是某次的运行输出:
running... 0
isInterrupted()... false
running... 1
isInterrupted()... false
running... 2
isInterrupted()... false
running... 3
isInterrupted()... false
running... 4
isInterrupted()... false
running... 5
isInterrupted()... false
running... 6
isInterrupted()... false
running... 7
isInterrupted()... false
running... 8
isInterrupted()... false
running... 9
isInterrupted()... false
running... 10
Interrupted... 
isInterrupted()... false
isInterrupted()... true
exit... 
 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved