class TestThread extends Thread{
private int sleepTime;
public TestThread(String name) {
super(name); //此处有super语句
sleepTime = (int ) (Math.random() * 6000);
}
public void run() {
try {
System.out.println(getName() + "going to sleep for" + sleepTime);
Thread.sleep(sleepTime);
}
catch(InterruptedException exception) {;}
System.out.println(getName() + "Finished");
}
}
public class HelloWorld extends Thread{
public static void main(String args[])
{
TestThread thread1 = new TestThread("thread1");
TestThread thread2 = new TestThread("thread2");
TestThread thread3 = new TestThread("thread3");
System.out.println("starting threads");
thread1.start();
thread2.start();
thread3.start();
}
}
执行结果
thread1-3字符能够正常显示
注释掉super(name);的话 不能正常显示
super(参数):调用基类中的某一个构造函数(应该为构造函数中的第一条语句)
调用super()必须写在子类构造方法的第一行,否则编译不通过。每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错。