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