Java如何通过实现Runnable接口创建线程?
这是创建线程的第二种方法。我们创建一个实现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.
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短