@Override @SuppressWarnings("unchecked") public <T> T execute(final CommandConfig config, final Command<T> command) { // 1. 从线程中拿到上下文 finalCommandContextcommandContext= Context.getCommandContext(); // 2. 获取对应的agenda,要执行的线程操作加入计划任务链表 // Execute the command. // This will produce operations that will be put on the agenda. 将命令操作放入agenda commandContext.getAgenda().planOperation(newRunnable() { @Override publicvoidrun() { commandContext.setResult(command.execute(commandContext)); } });
// Run loop for agenda 循环执行 executeOperations(commandContext); // 执行结束后,调用execution相关的变更事件,如果涉及的话 // At the end, call the execution tree change listeners. // TODO: optimization: only do this when the tree has actually changed (ie check dbSqlSession). if (commandContext.hasInvolvedExecutions()) { Context.getAgenda().planExecuteInactiveBehaviorsOperation(); executeOperations(commandContext); } // 最终返回执行结果 return (T) commandContext.getResult(); } /** * 循环在agenda中获取是否有需要执行的命令,有则执行 */ protectedvoidexecuteOperations(final CommandContext commandContext) { while (!commandContext.getAgenda().isEmpty()) { Runnablerunnable= commandContext.getAgenda().getNextOperation(); executeOperation(runnable); } } //线程的真正启动 publicvoidexecuteOperation(Runnable runnable) { if (runnable instanceof AbstractOperation) { AbstractOperationoperation= (AbstractOperation) runnable;
// Execute the operation if the operation has no execution (i.e. it's an operation not working on a process instance) // or the operation has an execution and it is not ended if (operation.getExecution() == null || !operation.getExecution().isEnded()) {
if (logger.isDebugEnabled()) { logger.debug("Executing operation {} ", operation.getClass()); }
runnable.run();
}
} else { runnable.run(); } }
@Override public CommandInterceptor getNext() { returnnull; } // 限制了CommandInvoker 必须是最后一个拦截器 @Override publicvoidsetNext(CommandInterceptor next) { thrownewUnsupportedOperationException("CommandInvoker must be the last interceptor in the chain"); }