Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

java - Java中的“可运行的实现”与“扩展线程”(“implements Runnable” vs “extends Thread” in Java)

From what time I've spent with threads in Java, I've found these two ways to write threads:

(从什么时候开始在Java中使用线程开始,我发现了以下两种编写线程的方法:)

With implements Runnable :

(与implements Runnable :)

public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call

Or, with extends Thread :

(或者,使用extends Thread :)

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call

Is there any significant difference in these two blocks of code ?

(这两个代码块有什么显着区别吗?)

  ask by user65374 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes: implements Runnable is the preferred way to do it, IMO.

(是的:IMO是实现Runnable的首选方法。)

You're not really specialising the thread's behaviour.

(您并不是真的专门研究线程的行为。)

You're just giving it something to run.

(您只是在给它一些东西来运行。)

That means composition is the philosophically "purer" way to go.

(这意味着合成是从哲学上讲“更纯净”的方式。)

In practical terms, it means you can implement Runnable and extend from another class as well.

(实际上 ,这意味着您可以实现Runnable并从另一个类进行扩展。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...