扩展Thread类并实现Runnable接口的方案 [英] Scenario of extending Thread class and implementing Runnable interface
问题描述
我是Java线程编程的新手,因此这是一个基本问题. (我检查了一下,但找不到以前问过的问题)
I am new to thread programming in Java and hence this basic question. (I checked, but could not find this question previously asked)
我读到可以通过继承Thread类或实现Runnable接口来创建线程. 我看到了两个代码都属于同一类.
I read that threads can be created either by inheriting the Thread class or by implementing the Runnable interface. I saw a code which had both to the same class.
public class ThreadExample extends Thread implements Runnable {
}
我想知道什么样的情况会发生什么,如果这有什么好处,那会是什么.
I was wondering what kind of situation would want this and if there is any advantage to this, what is it.
推荐答案
扩展Thread
和实现Runnable
是没有用的(Thread
已经实现了Runnable
).您几乎总是 想要实现Runnable
(并且 not 扩展Thread
).这样,您可以灵活地直接使用Thread
(不推荐)或使用java.util.concurrent
中较新的ThreadPool
实现之一(推荐).
extending Thread
and implementing Runnable
is useless (Thread
already implements Runnable
). You pretty much always want to implement Runnable
(and not extend Thread
). That gives you the flexibility of using a Thread
directly (not recommended) or using one of the newer ThreadPool
implementations in java.util.concurrent
(recommended).
这篇关于扩展Thread类并实现Runnable接口的方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!