[英]JAVA - Multithreading by Extending Thread Class - About Creating Objects
public class game extends Thread{
public void run() {
System.out.println("Sub-class must override the void run() method of Thread class!");
}
public static void main(String args[]) {
Thread t = new Thread();
t.start();
}
}
对于上面的这些代码行,控制台中什么也没有。 但是对于下面的这些代码:
public class game extends Thread{
public void run() {
System.out.println("Sub-class must override the void run() method of Thread class!");
}
public static void main(String args[]) {
game g = new game();
g.start();
}
}
我得到“子类必须重写Thread类的void run()方法!” 显示在控制台中。
您能帮我吗,为什么我需要创建一个子类的对象而不是Thread类的对象? 有什么不同? 对不起,我是一个新手。
这是因为在第一个代码中,该对象是没有任务要运行的默认线程。 您本可以给线程对象执行这样的任务,
public class game implements Runnable{
public void run() {
System.out.println("Sub-class must override the void run() method of Thread class!");
}
public static void main(String args[]) {
Thread t = new Thread(new game());
t.start();
}
}
在第二种情况下,您为线程(子类游戏)提供了默认任务以在其run
方法中打印。 在此处查看有关线程的更多信息
如果创建父类的实例,则编译器将不知道其子类。 这就是为什么您需要实例化父级操作的子类的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.