[JavaEE]如何唤醒Sleep中的线程

主线程调用子线程的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

转载于:https://www.cnblogs.com/spec-dog/p/3791043.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值