线程休眠sleep

文章展示了如何在Java中使用Thread.sleep()方法进行线程休眠,以此实现模拟倒计时器和每隔一秒打印当前时间的功能。在倒计时示例中,线程在每秒结束时减少计数,直到达到零。在时间打印示例中,程序不断更新并打印当前时间的小时、分钟和秒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程休眠sleep

  • sleep(时间)指定当前线程阻塞的毫秒数;
  • sleep存在异常InterruptedException;
  • sleep时间达到后线程进入就绪状态;
  • sleep可以模拟网络延时,倒计时等。;
  • 每一个对象都有一个锁,sleep不会释放锁;

使用Thread.sleep(millis ***);方法实现,会存在一个InterruptedException异常。

以下列举倒计时和打印当前时间为例

编写一个倒计时器

package com.thread;

import java.util.Scanner;

//模拟倒计时
public class TestSleep1 {
     public void timeDown(int time) throws InterruptedException {
          while (true){
               Thread.sleep(1000);
               System.out.println(time--);
               if (time <= 0){
                    System.out.println("计时结束!");
                    break;
               }
          }
     }

     public static void main(String[] args) {
          System.out.print("输入倒计时秒数:");
          Scanner scanner = new Scanner(System.in);
          int time = scanner.nextInt();
          try {
               new TestSleep1().timeDown(time);
          } catch (InterruptedException e) {
               e.printStackTrace();
          }
     }
}

模拟打印当前时间

package com.thread;

import java.text.SimpleDateFormat;
import java.util.Date;

//模拟打印当前时间
public class TestSleep2 {
    public void time(){
        Date date = new Date(System.currentTimeMillis());
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
                date = new Date(System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new TestSleep2().time();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值