嗨,我最近发现一个博客,其中指出:
Sometimes you may have to implement Runnable as well as subclass Thread. For instance, if creating a subclass of Thread that can execute more than one Runnable. This is typically the case when implementing a thread pool.
我不确定这个说法指的是什么场景。
你能帮我理解这种情况吗?
谢谢。
最佳答案
检查此链接:"implements Runnable" vs. "extends Thread"
正如乔恩·斯基特所说:
In practical terms, it means you can implement Runnable and extend from another class as well.
示例:
public class Worker extends Person implements Runnable {...}
您引用的内容是您实际上需要使用线程的子类来实现更复杂的机制。例如。您实现一个可以执行多个任务的线程。
public SimpleExecutionService extends Thread() {
private List<Runnable> myTasks;
public SimpleExecutionService(List<Runnable> tasks){
myTasks = tasks;
}
public void run() {
for(Runnable task: myTasks) {
task.run();
}
}
顺便说一下,这种并发机制已经存在很多了。
关于java - 当我们需要实现 Runnable 以及子类 Thread 时的场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646385/