Java如何使用Thread类的sleep方法?
下面是另一个使用Thread.sleep()方法的示例。在这个例子中,我们创建了ThreadSleepAnotherDemo的两个实例,我们给每个线程一个名称和休眠间隔,这样我们就可以看到如何执行线程。
package org.nhooo.example.lang;
import java.util.Calendar;
public class ThreadSleep implements Runnable {
private String threadName;
private long sleep;
public ThreadSleep(String threadName, long sleep) {
this.threadName = threadName;
this.sleep = sleep;
}
// 启动线程时将调用run()方法。
public void run() {
System.out.println("Start thread [" + this.threadName + "]");
try {
while (true) {
// 将线程暂停“睡眠”毫秒。"sleep" milliseconds.
Thread.sleep(this.sleep);
System.out.println("[" + threadName + "]" +
Calendar.getInstance().getTime());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finish thread [" + this.threadName + "]");
}
public static void main(String[] args) {
Thread thread1 = new Thread(new ThreadSleep("FirstThread", 1000));
Thread thread2 = new Thread(new ThreadSleep("SecondThread", 3000));
// 启动线程
thread1.start();
thread2.start();
}
}这些是上面的代码片段生成的示例输出:
Start thread [FirstThread] Start thread [SecondThread] [FirstThread]Sun Aug 13 10:42:53 WITA 2017 [FirstThread]Sun Aug 13 10:42:54 WITA 2017 [SecondThread]Sun Aug 13 10:42:55 WITA 2017 [FirstThread]Sun Aug 13 10:42:55 WITA 2017 [FirstThread]Sun Aug 13 10:42:56 WITA 2017
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短