“实现Runnable” vs“扩展线程”在Java中 [英] "implements Runnable" vs "extends Thread" in Java

查看:146
本文介绍了“实现Runnable” vs“扩展线程”在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我在Java中使用线程开始,我发现了这两种编写线程的方法:

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

使用实现Runnable

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

或者,扩展线程

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 ?

推荐答案

是:实现 Runnable 是首选方法,IMO。你并不是真正专注于线程的行为。你只是给它一些东西来运行。这意味着撰写哲学更纯粹的方式。

Yes: implements Runnable is the preferred way to do it, IMO. 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.

实用术语中,这意味着您可以实现 Runnable 并从另一个类扩展为好吧。

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

这篇关于“实现Runnable” vs“扩展线程”在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆