码迷,mamicode.com
首页 > 编程语言 > 详细

如何唤醒Sleep中的线程

时间:2014-06-18 17:26:12      阅读:523      评论:0      收藏:0      [点我收藏+]

标签:class   tar   2014   string   art   new   

主线程调用子线程的interrupt()方法,导致子线程抛出InterruptedException, 在子线程中catch这个Exception,不做任何事即可从Sleep状态唤醒线程,继续执行。 如下测试。

public class SleepThreadTest {

    public static void main(String[] args){
        Thread myThread = new Thread(new TestThread(1));
        myThread.start();
        try {
            Thread.sleep(3000);
            myThread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        
        
    }
    
    private static class TestThread implements Runnable{
        private int i;
        public TestThread(int i){
            this.i = i;
        }

        @Override
        public void run() {
            while(i<10){
                System.out.println(i + "   time:" + new Date());
                i++;
                if(i==4){
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e1) {
                        System.out.println("interrupt myThread...");
                    }

                }
            }
        }
        
    }
}

result:

1   time:Mon Jun 16 15:19:56 CST 2014
2   time:Mon Jun 16 15:19:56 CST 2014
3   time:Mon Jun 16 15:19:56 CST 2014
interrupt myThread...
4   time:Mon Jun 16 15:19:59 CST 2014
5   time:Mon Jun 16 15:19:59 CST 2014
6   time:Mon Jun 16 15:19:59 CST 2014
7   time:Mon Jun 16 15:19:59 CST 2014
8   time:Mon Jun 16 15:19:59 CST 2014
9   time:Mon Jun 16 15:19:59 CST 2014

如何唤醒Sleep中的线程,布布扣,bubuko.com

如何唤醒Sleep中的线程

标签:class   tar   2014   string   art   new   

原文地址:http://www.cnblogs.com/spec-dog/p/3791043.html

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