• 多线程中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. }

    运行结果

  • 相关阅读:
    C++并发与多线程(8) | 互斥量
    深度学习笔记Week4
    华为OD 数列描述(100分)【java】A卷+B卷
    flink的window和windowAll的区别
    goquery库编写程序
    Ruby 环境变量
    查找算法【哈希表】 - 简介
    photoshop如何使用PS中的吸管工具吸取软件外部的颜色?
    Computer Architecture Subtitle:Engineering And Technology
    du命令:显示文件或者目录的大小
  • 原文地址:https://blog.csdn.net/m0_50370837/article/details/126771061