多线程中sleep()和interrupt()的结合使用

在多线程Thread中有两个方法, sleep()和interrupt()

一、sleep方法

 返回值          方法                                        使用描述
static voidsleep(long millis)使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行),具体取决于系统定时器和调度程序的精度和准确性。
static voidsleep(long millis, int nanos) 导致正在执行的线程以指定的毫秒数加上指定的纳秒数来暂停(临时停止执行),这取决于系统定时器和调度器的精度和准确性。 

使用该方法时, 需要处理InterruptedException异常, 也可以直接抛出, 但是一般都会把它处理掉. 

try {
       Thread.sleep(long millis);
    } catch (InterruptedException e) {
       e.printStackTrace();
}

二、interrupt

              返回值       方法                                使用描述
               void   interrupt()                             中断这个线程

拓展方法

        返回值        方法                                使用描述
        static boolean interrupted()                        测试当前线程是否中断
        boolean isInterrupted()                        测试这个线程是否被中断

三、代码演示

package com.softeem.wolf.thread;

/**
 * Created by 苍狼
 * Time on 2022-09-08
 */
public class ThreadTest02 {
    public static void main(String[] args) {
        Thread t1 = new Thread(){
            @Override
            public void run() {
                System.out.println("AA:惊雷,这通天修为....");
                try{
                    Thread.sleep(1000000);
                }catch(InterruptedException inter){
                    inter.printStackTrace();
                    System.out.println("AA中断了....");
                }
                System.out.println("BB,你唱的啥玩意啊....");
            }
        };

        Thread t2 = new Thread(){
            @Override
            public void run() {
                System.out.println("BB:你唱的啥?");
                for (int i = 0; i < 5; i++) {
                    System.out.println("BB:无所谓...");
                    try{
                        Thread.sleep(1000);
                    }catch (InterruptedException inter) {
                        inter.printStackTrace();
                    }
                }
                System.out.println("BB:唱完了");
                t1.interrupt();
            }
        };

        t1.start();
        t2.start();
    }
}

运行结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值