我在以以下参考中描述的方式运行可运行对象时遇到问题:
TasksHandler handler = TasksHandler.builder()
.task("1", sleepRunnable())
.task("2", sleepRunnable())
.task("3", sleepRunnable())
.build();
handler.runTasks();
我的实现如下所示:
private Action<States, Events> getUnlockedAction() {
return new Action() {
@Override
public void execute(StateContext sc) {
System.out.println("in action..");
handler = new TasksHandler.Builder().taskExecutor(taskExecutor()).task("1", dp.runProcess(1)).build();
handler.addTasksListener(new MyTasksListener());
handler.runTasks();
System.out.println("after action..");
}
};
}
TaskExecutor 的初始化如下所示:
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
te.setMaxPoolSize(50);
te.setThreadNamePrefix("LULExecutor-");
te.setCorePoolSize(25);
te.initialize();
return te;
}
我的 dp (DataProcessor) 代码如下所示:
@Component
@Qualifier("dataProcessor")
public class ADataProcessor {
public Runnable runProcess(final int i) {
return new Runnable() {
@Async
@Override
public void run() {
long delay = (long) ((Math.random() * 10) + 1) * 1000;
System.out.println("In thread " + i + "... sleep for " + delay);
try {
Thread.sleep(delay);
} catch (InterruptedException ex) {
Logger.getLogger(FSMFactoryConfig.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("After thread " + i + "...");
}
};
}
}
当我执行我的代码时,我会毫不拖延地看到“行动中……”和“行动后……”的消息。
当我使用以下内容时:
taskExecutor().execute(dp.runProcess(1));
taskExecutor().execute(dp.runProcess(2));
taskExecutor().execute(dp.runProcess(3));
taskExecutor().execute(dp.runProcess(4));
taskExecutor().execute(dp.runProcess(5));
taskExecutor().execute(dp.runProcess(6));
我得到了我对使用 TasksHandler 的期望..
- 状态更改为解锁
- 在线程 2... 睡 10000
- 在线程 3... 睡 5000
- 在线程 4... 睡 8000
- 在线程 5... 睡 4000
- 在线程 6... 睡 4000
- 在线程 1... 睡 9000
- 2016 年 1 月 13 日下午 12:32:13 - org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor 初始化
- 信息:初始化 ExecutorService
- 状态更改为 LOCKED
- 线程 5 之后...
- 在线程 6 之后...
- 在线程 3 之后...
- 线程 4 之后...
- 在线程 1 之后...
- 在线程 2 之后...
使用 TasksHandler 时,睡眠延迟之前或之后的消息均不显示。所以我的问题是,我如何实际执行我的可运行文件?如果我做得正确,我应该检查什么?