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

时间:2015-04-03 22:26:24

标签: java multithreading

任务如下。

  

有一系列任务。有必要创建一个定期出现这些问题的线程。

脑海中浮现的是以下机制。创建一个继承自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    |
                |----------------------->|
                       .   .    .

1 个答案:

答案 0 :(得分:1)

您应该只使用一个类似。

的线程创建一个ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(1);

然后,当您想要向队列添加任务时,请创建一个新的runnable并提交它。

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

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

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