java - 如何组织一系列运行任务?

标签 java multithreading

任务如下。

There is a queue of tasks. It is necessary to create a thread that periodically these problems will come.

我想到的是以下机制。创建一个继承自 Thread 的类和一个 run 方法来执行如下操作:

while (! isInterrupted ()) {
    while (executedTask! = null) {
       // Execute task
       // Push callback about successfully processed task
       executedTask == null;
    }
}

但是看看代码,直觉表明有人是我“幕后黑手”:)

所以我想问一下如何更好地实现这个任务。它不是代码,只是文字。如果能提供示例链接,我将不胜感激。

        ------------------     -------------------
        |   TaskHolder   |     |   WorkerThread  |            
        ------------------     -------------------
                |                        |
         task   |      execute           |
        ------->|----------------------->|
         task#2 |              hard-time task worked
        ------->|queue task until current|
                |task is processed       |
         task#3 |                        |
        ------->|queue task until current|
                |task is processed       |
         task#4 |                        |
        ------->|queue task until current|
                |task is processed       |
         task#5 |                        |
        ------->|queue task until current|
                |task is processed       |
         task#6 |                        |
        ------->|queue task until current|
                |task is processed       |
                |                        |
                |                        |
                |                 task finished
                |    return result       |
                |<-----------------------|
                |                        |
                |pop task#2 from queue   |
                |      execute task#2    |
                |----------------------->|
                       .   .    .

最佳答案

您应该创建一个只有一个线程的 ExecutorService。

ExecutorService executor = Executors.newFixedThreadPool(1);

然后,当您想要将任务添加到队列中时,创建一个新的可运行并提交它。

executor.submit(new Runnable() {
    public void run() {
            //your code here
    }
});

单线程 ExecutorService 一次仅运行一个任务,并将您提交给它的新任务排队并按照您提交的顺序运行它们。

作为奖励,如果您拥有多线程环境并希望避免复杂的同步和锁定问题,此模式可能特别有用。

关于java - 如何组织一系列运行任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29440501/

相关文章:

java - 得到 'IOException: hostname was not verified' ,尽管给定的主机名(IP 地址)与通用名称匹配

java - JTable - 复选框添加 Action 监听器

c++ - 如何以编程方式判断两个变量是否位于同一个堆栈上? (在 Windows 中)

Java 扩展 vs 对象引用?

java - 一个接受通配符列表和函数的函数?

java - 什么是 Java 中的 IncompatibleClassChangeError 异常?

PHP + pthreads : Build one big object - parallel-processing

c - 多任务下与UART FIFO相关的Bug

android - 在 GPS 应用程序启动时显示进度对话框

SQL 问题 - 大量反式和 PK 违规