简单的例子:
class Test{
public Test() {
System.out.println("create test ..");
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new Test();
}
}
}
输出显而易见:
而实现Runnable接口的实现类却出现让我纳闷的情况:
public class SimpleDaemons implements Runnable {
public SimpleDaemons() {
System.out.println("create thread ..");
}
public static void main(String[] args) {
for (int i = 5; i < 5; i++) {
new SimpleDaemons();
}
}
@Override
public void run() {
try {
while (true) {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
}
} catch (InterruptedException e) {
System.out.println("sleep() interrupted");
}
}
}
不理解的输出,是没有在控制台上打印无参构造函数中的语句。
疑问:Runnable实现类,创建对象时,不会调用默认的无参构造函数吗?
我觉得你肯定是在逗我,你的for循环int=5,i< 5,它都进不去,走个毛啊
Runnable只是一个接口,是不存在构造方法的。要实现runnable要实例化Thread类:Thread t = new Thread(实现runnable接口类的对象),t.start()
重写一个类后再想调用无参构造器你就得super();
另外估计你就是在实验语法,正常没有这么写的,都是内部类开线程实现runnable