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 祝福语怎么写大全简短
18 白日庆典祝福语简短英语