// 定义线程启动时 调用的方法 public void run() { ExecutorService es = Executors.newFixedThreadPool( AppConfigurator.getInstance().getIntConfig("rms.delayWorker.sessionCount", 5)); while (true) { try { // 该线程先休眠1分钟 sleep(1000L); // 根据线程开发,判断是否继续执行 if (shouldStop) break; // 迭代该线程集合,取出每个线程 Iterator<Map.Entry<String, PortalStackFileProcess>> it = sessions.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, PortalStackFileProcess> m = it.next(); // 获得每一个线程对象 PortalStackFileProcess process = m.getValue(); // 如果该对象不为空,则将该线程的延时时间减一分钟 if (process != null) { process.decDelaSeconds(); // 判断该线程是否可以执行了,如果为true,则从线程池中删除该线程,并立刻执行该线程 if (process.isTime()) { it.remove(); es.execute(process); } } } } catch (InterruptedException e) { e.printStackTrace(); break; } } es.shutdown(); }
// 向线程集合中注入线程 public void startSession(String id, long cspId, String fullFilePath) { // 根据线程的id得到该线程对象 PortalStackFileProcess process = sessions.get(id); // 设置线程延时执行的时间 Integer delaySeconds = AppConfigurator.getInstance().getIntConfig("rms.delayWorker.delaySeconds", 2); // 如果集合中已存在该线程,则初始化线程的执行时间 if (process != null) { process.setDelaySeconds(delaySeconds); } else { // 否则,就实例化新的线程,并加入到线程集合中 process = new PortalStackFileProcess(id, cspId, fullFilePath); process.setDelaySeconds(delaySeconds); sessions.put(id, process); } }