简体   繁体   English

JAVA-通过扩展线程类进行多线程-关于创建对象

[英]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();
    }
}

For these lines of code above I got nothing in the console. 对于上面的这些代码行,控制台中什么也没有。 But for these codes below: 但是对于下面的这些代码:

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();
    }
}

I got "Sub-class must override the void run() method of Thread class!" 我得到“子类必须重写Thread类的void run()方法!” shown in the console. 显示在控制台中。

Could you help me, why I need to create an object of the sub-class rather than an object of the Thread class? 您能帮我吗,为什么我需要创建一个子类的对象而不是Thread类的对象? What's the difference? 有什么不同? Sorry I am a total novice. 对不起,我是一个新手。

That's because in the first code the object is a default thread that has no task to run. 这是因为在第一个代码中,该对象是没有任务要运行的默认线程。 You could have given the thread object a task like this, 您本可以给线程对象执行这样的任务,

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();
    }
}

Whereas in the second case you give the Thread (its Sub-class Game) a default task to print in its run method. 在第二种情况下,您为线程(子类游戏)提供了默认任务以在其run方法中打印。 See more about threads here 在此处查看有关线程的更多信息

If you create an instance of the parent class, the compiler will not know about its child. 如果创建父类的实例,则编译器将不知道其子类。 That is why you need to instantiate the sub class oppesed to the parent. 这就是为什么您需要实例化父级操作的子类的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM