gpt4 book ai didi

java - 为什么 Thread 不是抽象类而 start() 不是 final?

转载 作者:IT老高 更新时间:2023-10-28 11:51:48 31 4
gpt4 key购买 nike

为什么 Thread 类被实现为常规类,而不是 run() 方法为抽象的 abstract 类。

它可能会带来任何问题吗?或者这样有什么用?

另外,Thread.start() 方法应该是一个非常具体的方法任何其他类都无法实现其功能(如果我没记错的话) .因此,我猜 final 关键字比任何其他方法都更适合此。

但是我可以覆盖这个方法并随意使用它,

public class Test extends Thread {
public static void main (String... args) {
Thread test = new Test();
test.start();
}

@Override
public void run() {
System.out.println("New thread started...");
}

@Override
public void start() {
System.out.println("Did anyone tell you I will spawn a new thread??");
}
}

显然只是打印出来的,

Did anyone tell you I will spawn a new thread??

除了让取代你的工程师感到困惑之外,超越还有什么用处?

如果不是,为什么 Thread 类中没有将方法声明为 final?

最佳答案

你当然可以选择朝自己的脚开枪,但这并不意味着你必须这样做。

Why was the Thread class implemented as a regular class and not an abstract class with run() method being abstract.

因为创建启动线程的推荐方法不是子类化 Thread。推荐的方法是定义一个 Runnable,并将其作为参数传递给 Thread 构造函数:

Runnable r = new Runnable() {
@Override
public void run() {
...
}
};
Thread t = new Thread(r);
t.start();

And hence I guess the final keyword would be apt for this more than any other method.

是和不是。你不能用你自己的实现替换 start() 的实现,但是如果你愿意,你可以在 start() 中做附加的事情:

@Override
public void start() {
System.out.println("Did anyone tell you I will spawn a new thread??");
super.start();
}

也就是说,如果今天从头开始重新设计 Java,那么设计很有可能会有所不同。请记住,这个类可以追溯到 Java 1.0,并且仍然向后兼容。

关于java - 为什么 Thread 不是抽象类而 start() 不是 final?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202946/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com