Java sleep():让线程休眠(附带实例)
在 Java 程序中,如果需要让当前正在执行的线程暂停一段时间,则通过调用 Thread 类的静态方法 sleep() 可以使其进入计时等待状态,让其他线程有机会执行。
sleep() 方法是 Thread 的静态方法,有以下两个重载方法:
线程在休眠的过程中如果被中断,则该方法抛出 InterruptedException 异常,所以调用时要捕获异常。
【实例】设计一个数字时钟,在桌面窗口中显示当前时间,每隔 1 秒自动刷新。
sleep() 方法是 Thread 的静态方法,有以下两个重载方法:
- public static void sleep(long millis) throws InterruptedException:在指定的毫秒数 millis 内让当前正在执行的线程休眠;
- public static void sleep(long millis,int nanos) throws InterruptedException:在指定的毫秒数 millis 加指定的纳秒数 nanos 内让当前正在执行的线程休眠。
线程在休眠的过程中如果被中断,则该方法抛出 InterruptedException 异常,所以调用时要捕获异常。
【实例】设计一个数字时钟,在桌面窗口中显示当前时间,每隔 1 秒自动刷新。
import java.awt.Container;
import java.awt.FlowLayout;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DigitalClock extends JFrame implements Runnable {
JLabel jLabel1, jLabel2;
public DigitalClock(String title) {
jLabel1 = new JLabel("当前时间:");
jLabel2 = new JLabel();
Container contentPane = this.getContentPane(); // 获取窗口的内容空格
contentPane.setLayout(new FlowLayout()); // 设置窗口为流式布局
this.add(jLabel1); // 把标签添加到窗口中
this.add(jLabel2); // 把标签添加到窗口中
// 单击关闭窗口时退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null); // 设置窗口显示在屏幕中间
this.setSize(300, 200); // 设置窗口尺寸
this.setVisible(true); // 使窗口可见
}
public void run() {
while (true) {
String msg = getTime(); // 获取时间信息
jLabel2.setText(msg); // 在标签中显示时间信息
try {
Thread.sleep(1000); // 休息1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 获取系统当前时间
public String getTime() {
// 创建时间对象并得到当前时间
Date date = new Date();
// 创建时间格式化对象,设定时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时MM分ss秒");
// 格式化当前时间,得到当前时间字符串
String dt = sdf.format(date);
return dt;
}
// 主方法
public static void main(String[] args) {
// 创建时钟窗口对象
DigitalClock dc = new DigitalClock("数字时钟");
// 创建线程对象
Thread thread = new Thread(dc);
// 启动线程
thread.start();
}
}
程序的运行结果为:
当前时间:2025年06月03日 14时30分15秒
让线程睡眠的目的是让线程让出 CPU 资源,当睡眠结束后,线程会自动苏醒,进入可运行状态。
ICP备案:
公安联网备案: