簡體   English   中英

如何順序執行ExecutorService中的任務?

[英]How to execute tasks in ExecutorService sequentially?

我有三個連接的線程,即第二個線程在第一個死后執行。

這是我的代碼:

public class Main {
    public static void main(String args[]) throws Exception {
        final Thread thrdA = new Thread(() -> System.out.println("Message 1"));
        final Thread thrdB = new Thread(() -> System.out.println("Message 2"));
        final Thread thrdC = new Thread(() -> System.out.println("Message 3"));

        thrdA.start();
        thrdA.join();
        thrdB.start();
        thrdB.join();
        thrdC.start();
        thrdC.join();

    }
}

如何使用ExecutorService而不是三個線程對象來實現此功能?

如果您想要/需要的是一個接一個地執行一組作業,但要在與主應用程序線程不同的單個線程中Executors#newSingleThreadExecutor ,請使用Executors#newSingleThreadExecutor

ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(() -> System.out.println("Message 1"));
es.submit(() -> System.out.println("Message 2"));
es.submit(() -> System.out.println("Message 3"));
es.shutdown();

您可以將SingleThread ExecutorService與future.get()方法一起使用來控制線程的順序執行。

DummyTask類

import java.util.concurrent.Callable;

public class DummyTask implements Callable<Integer>
{

int taskId;

public DummyTask(int taskId) {
    this.taskId = taskId;
}

@Override
public Integer call() throws Exception
{
    System.out.println("excuting task... Task Id: " + taskId);
    return taskId;
}

}

順序執行類

package com.amit.executorservice;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class SequentialExecution 
{
public static void main(String[] args) throws InterruptedException, ExecutionException {

    DummyTask task1 = new DummyTask(1);
    DummyTask task2 = new DummyTask(2);
    DummyTask task3 = new DummyTask(3);
    Future<Integer> result = null;
    ExecutorService executor = Executors.newSingleThreadExecutor();

    result = executor.submit( task1 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    result = executor.submit( task2 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    result = executor.submit( task3 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    executor.shutdown();

}
}

輸出量

excuting task... Task Id: 1
excuting task... Task Id: 2
excuting task... Task Id: 3

輸出將始終相同,並且所有任務將按順序執行。

如果您已經在應用程序中使用了線程池,則可以通過零線程代理串行執行器重復使用它,而無需創建特殊的單線程線程池。 我的Github存儲庫CodeSamples中 的Executor接口javadoc部分描述了一種實現,另一種是優化的實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM