其实代码第一行是package ....,不过是在公司写的,所以删除了。
import java.util.Date;
public class RunnableTest implements Runnable {
private Date date = new Date();
private Thread timeThread = null;
public void start() {
timeThread = new Thread(this);
timeThread.start();
}
public void stop() {
timeThread = null;
}
@SuppressWarnings("static-access")
public void run() {
Thread currentThread = Thread.currentThread();
while (timeThread == currentThread) {
date = new Date();
System.out.println(date);
try {
timeThread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
RunnableTest test = new RunnableTest();
test.start();
}
}
本文提供了一个Java中实现线程的示例代码,通过继承Runnable接口来创建一个可以定期更新并打印当前日期时间的线程。该示例展示了如何启动和停止线程,以及如何在循环中使用sleep方法使线程休眠。
958

被折叠的 条评论
为什么被折叠?



