如何以具体顺序使用ExecutorService执行线程?
在我的程序中,我有几个命令,它们由命令执行程序类执行。我需要使用 ExecutorService 依次执行 4 个命令(在创建新命令之前不显示用户)。
执行环境:
public class ConcurrentCommandExecutionEnvironment {
private static final int POOL_SIZE = 4;
private static final Logger log = Logger.getLogger(ConcurrentCommandExecutionEnvironment.class);
public void readArgsAndExecuteCommand(String[] props) {
if (props.length == 0) {
throw new IllegalArgumentException("Error: no params entered");
}
ExecutorService execService = new ThreadPoolExecutor(
4,
4,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()
);
ReentrantLock lock = new ReentrantLock();
CommandStore commandStore = new CommandStore();
CommandExecutor commandExecutor = new CommandExecutor(
new CreateUserCommand(commandStore),
new GetUserListCommand(commandStore),
new CreateTaskCommand(commandStore),
new GetTasksListCommand(commandStore),
new GetTaskByUsernameCommand(commandStore),
new CompleteTaskCommand(commandStore),
new DeleteUserCommand(commandStore),
new CreateUserAndTaskCommand(commandStore)
);
execService.execute(() -> {
commandExecutor.createUserAndTask(props);
});
execService.execute(() -> {
commandExecutor.getUsers(props);
});
execService.execute(() -> {
commandExecutor.getTasks(props);
});
execService.shutdown();
}
以前我没有使用“同步”运算符来处理 ExecutorService 和同步线程。我可以像这样在这里使用它吗(使用 commandExecutor 实例作为互斥锁并在每个线程中同步它,如下例所示):
execService.execute(() -> {
synchronized (commandExecutor) {
commandExecutor.createUserAndTask(props);
}
});
或者使用 ExecutorService 我应该以另一种方式进行?
回答
Executors.newSingleThreadExecutor
如果您需要顺序运行多个任务,请将它们提交给单线程执行程序服务。
ExecutorService es = Executors.newSingleThreadExecutor() ;
…
es.submit( task1 ) ;
es.submit( task2 ) ;
es.submit( task3 ) ;
或者重新考虑您是否甚至需要执行程序服务。如果原始线程等待一系列任务在单线程执行器服务中按顺序运行,则原始线程也可以自己运行任务。如果等待单个线程,则线程化没有意义。