Why is Thread not an abstract class and start() not final?

后端 未结 4 1136
北海茫月
北海茫月 2021-01-30 10:05

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

Will it po

4条回答
  •  独厮守ぢ
    2021-01-30 10:51

    You can of course choose to shoot yourself in the foot, but that doesn't mean you must.

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

    Because the recommended way to create a start a thread is not to subclass Thread. The recommended way is to define a Runnable, and pass it as argument to the Thread constructor:

    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.

    Yes and no. You can't replace the implementation of start() by your own implementation, but you can do additional things in start() if you want:

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

    That said, if Java was redesigned from scratch today, there is a good chance the design would be different. Remember that this class dates from Java 1.0, and is still backward-compatible.

提交回复
热议问题