【发布时间】:2015-12-21 21:47:27
【问题描述】:
我有一个程序,我希望每次创建它的实例时都在 new Thread 上运行一个特定的类。为此,我使用了多线程的extend Thread 继承方法。但是,我想知道的是:当我为某个类extend Thread 时,我调用的该类的每个方法(比如在构造函数中或稍后)是否会在线程上运行,或者只会在调用run() 方法在新线程上运行?
示例:
public class Entity extends Thread {
Entity() {
super("Bob");
start();
method2(); //will this run on the new Thread alongside the one called in run()?
}
public void run() {
method1(); //will only this method run on the new Thread?
}
int method1() {
return 1;
}
int method2() {
return 2;
}
}
或:
public class World {
public static void main(String args[]) {
Entity example = new Entity();
example.method2(); //will this run on the new Thread?
}
}
【问题讨论】:
-
你在尝试的时候看到了什么?
-
我不能完全确定,我会尝试编写一个输出更明显的程序。当我添加打印语句时,导致所有数字都立即打印出来。我将尝试使用 Thread.sleep(),
-
1-不要,您应该更喜欢使用
Runnable并将其包装为Thread的实例和 2- 不,或者更重要的是,除非方法被执行从Thread的run方法的上下文中 -
因为您没有创建一种新的
Thread(这是扩展所暗示的)。您只需要在一个代码中运行一些代码。 -
run方法在Thread中的事实并不意味着它在新线程上运行:它在调用它的线程上运行。例如如果您调用thread.start(),它将在一个新线程上,但如果您直接调用thread.run(),则不会。
标签: java multithreading inheritance extends java-threads