线程的唤醒interrupt()方法

线程的唤醒interrupt()方法:

如果一个线程睡眠太久了,有没有办法唤醒它吗?
有的,使用"对象.interrupt()"方法。

这个方法的意思是:中断打扰,一盆冷水过去,线程立马醒了,够形象。

唤醒的机制是靠异常机制,当使用这个方法之后,对应的线程的sleep进入catch异常捕捉,表明睡眠异常,有人中断了这个线程的睡眠。

测试代码:

public class Test07 {
    public static void main(String[] args) {
        // 创建线程对象
        Thread thread1 = new Thread(new MyRun07());

        // 顺便改个名字
        thread1.setName("t1");

        // 启动线程
        thread1.start();

        // 假设main主线程5秒钟做完了事,要求thread1线程醒来
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 叫醒thread1线程,终止它的睡眠
        thread1.interrupt();

    }
}

class MyRun07 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "--begin");

        // 让当前这个线程休眠1年,哈哈

        // 注意:这里的sleep()不能上抛异常,只能自己捕捉
        // 因为父类中的run()方法没有抛出任何异常,子类重写的方法不能抛出更多的异常
        try {
            Thread.sleep(1000L * 60 * 60 * 24 * 365);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + ":难道有人叫我?");
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + "--over");
    }
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值