java - 当我们需要实现 Runnable 以及子类 Thread 时的场景

标签 java multithreading threadpool

嗨,我最近发现一个博客,其中指出:

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/

相关文章:

c++ - boost::mutex 发布 VS 调试构建

java - 我的notifyAll() 有什么问题吗?

java - 嵌入式系统中线程池的优点

c# - ThreadPool SetMaxThreads 和 SetMinThreads 魔数(Magic Number)

java - import com.fasterxml.jackson.databind.ObjectMapper 无法解析

java - 如何从 CharsetDecoder 的 .decode() 生成 UnmappableCharacterException?

java - 我应该在 Android 上支持对象池而不是新对象吗?

java - 复杂代码/算法优化(例如简化)的困境

java - 清除 Thread.interrupt() 标志的方法

java - 带有线程池的嵌套循环