java:利用TimeUnit的函数sleep让当前线程休眠一段时间

本文介绍了Java中`TimeUnit.sleep`函数的基本用法,强调了当传入参数小于或等于0时的处理,并通过代码示例展示了如何在线程中使用该函数来控制休眠时间。
摘要由CSDN通过智能技术生成

java.util.concurrent.TimeUnit类的函数sleep(long timeout)让当前线程休眠一段时间,如果参数timeout的值小于或等于0,就不休眠。
这个函数其实是java.lang.Thread的静态函数sleep的一种方便用法。

代码示例:

package com.thb;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Test5 {

    public static void main(String[] args) {
        // 创建一个线程
        Thread thread1 = new Thread(() -> {
            // 打印当前线程名称
            System.out.println("enter thread: " + Thread.currentThread().getName());
            // 打印当前时间
            System.out.println("curren time: " + new Date(System.currentTimeMillis()));
            try {
                // 休眠5秒钟
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 打印当前线程名称
            System.out.println("left thread: " + Thread.currentThread().getName());
            // 打印当前时间
            System.out.println("curren time: " + new Date(System.currentTimeMillis()));
        }, "thread1");
        // 启动线程
        thread1.start();

        // 打印当前线程名称
        System.out.println("current thread: " + Thread.currentThread().getName());
    }

}

一次运行输出结果:

enter thread: thread1
current thread: main
curren time: Mon Dec 25 12:14:42 HKT 2023
left thread: thread1
curren time: Mon Dec 25 12:14:47 HKT 2023
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值