这是创建线程的第二种方法。我们创建一个实现java.lang.Runnable接口的对象。有关另一个示例,请参见如何通过扩展Thread类来创建线程。
package org.nhooo.example.lang;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimeThread implements Runnable {
private DateFormat df = new SimpleDateFormat("hh:mm:ss");
// 当该可运行对象的线程运行时,将调用run()方法
// 开始。
@Override
public void run() {
while (true) {
Calendar calendar = Calendar.getInstance();
System.out.format("Now is: %s.%n", df.format(calendar.getTime()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TimeThread time = new TimeThread();
Thread thread = new Thread(time);
thread.start();
}
}此代码的示例结果是:
Now is: 04:44:59. Now is: 04:45:00. Now is: 04:45:01. Now is: 04:45:02. Now is: 04:45:03.