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


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

    一、sleep方法

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

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

    1. try {
    2. Thread.sleep(long millis);
    3. } catch (InterruptedException e) {
    4. e.printStackTrace();
    5. }

    二、interrupt

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

    拓展方法

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

    三、代码演示

    1. package com.softeem.wolf.thread;
    2. /**
    3. * Created by 苍狼
    4. * Time on 2022-09-08
    5. */
    6. public class ThreadTest02 {
    7. public static void main(String[] args) {
    8. Thread t1 = new Thread(){
    9. @Override
    10. public void run() {
    11. System.out.println("AA:惊雷,这通天修为....");
    12. try{
    13. Thread.sleep(1000000);
    14. }catch(InterruptedException inter){
    15. inter.printStackTrace();
    16. System.out.println("AA中断了....");
    17. }
    18. System.out.println("BB,你唱的啥玩意啊....");
    19. }
    20. };
    21. Thread t2 = new Thread(){
    22. @Override
    23. public void run() {
    24. System.out.println("BB:你唱的啥?");
    25. for (int i = 0; i < 5; i++) {
    26. System.out.println("BB:无所谓...");
    27. try{
    28. Thread.sleep(1000);
    29. }catch (InterruptedException inter) {
    30. inter.printStackTrace();
    31. }
    32. }
    33. System.out.println("BB:唱完了");
    34. t1.interrupt();
    35. }
    36. };
    37. t1.start();
    38. t2.start();
    39. }
    40. }

    运行结果

  • 相关阅读:
    VisualSVN 8.1 Release Notes Date: November 3, 2022
    leetcode刷题方法总结—数组全解
    Java架构师系统架构设计资源估算
    数组Array.prototype原型方法学习-30分钟学完数组全部操作 原创
    Android Studio新建项目缓慢解决方案
    printf如何打印指定长度-防止非NUL结尾的字符串造成的读越界漏洞的方法
    虚拟机Ubuntu20.04 网络连接器图标开机不显示怎么办
    C#接口多继承的写法
    Load-balanced-online-OJ-system 负载均衡的OJ系统项目
    MySQL 中 DATETIME 和 TIMESTAMP 时间类型的区别及使用场景
  • 原文地址:https://blog.csdn.net/m0_50370837/article/details/126771061