Thread 其实内部也是实现了Runnable接口,两者都是将要实现的方法放在 run()方法中,只不过Thread要用start()方法调用run() 《其实直接调用run()也可以,不过sun可能在start实现了一些安全机制,所以还是通过start()调用run()比较好》》, 而Runnable可以直接调用run().因为java不支持多继承,所以当我们要继承另一个类,又要实现多线程时,就要使用runnable, 其他的场合,一般我都用thread.下面是两个例子。它实现每隔一秒在控制台打印时间
import java.util.Calendar;
/**
* @author eva
* 继承thread 类
*/
public class ClockThread extends Thread {
private Calendar now;
public void run() {
while (true) {
now = Calendar.getInstance();
System.out.println(now.getTime());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public ClockThread(String arg0) {
super(arg0);
}
}
import java.util.Calendar;
/**
* @author eva
* 实现runnable接口
*/
public class ClockRunnable implements Runnable {
private Calendar now;
public void run() {
while (true) {
this.now = Calendar.getInstance();
System.out.println(now.getTime());
/*
* 使线程休息一秒
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public ClockRunnable() {
super();
}
}
/**
* @author eva
* 测试类
*/
public class MainCpp {
/**
* @param args
*/
public static void main(String[] args) {
/*
* 测试thread
*/
ClockThread display = new ClockThread("extends Thread");
display.run();
/*
* 测试runnable
*/
//ClockRunnable display = new ClockRunnable();
//display.run();
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/11704089/viewspace-366419/
,如需转载,请注明出处,否则将追究法律责任。