我们可以在java中有多个预定的线程池吗?

时间:2016-04-06 06:12:11

标签: java multithreading rest scheduled-tasks threadpool

所以基本上我对多线程非常陌生。 我想以不同的间隔安排5个任务。 所以我发现了提供调度的执行器服务。

以不同的间隔启动五个任务。我不确定可以做到。

可能一个或多个任务可能同时开始。 所以我想为所有任务创建多个线程池。他们还会碰撞吗? 如果我启动多个线程池,我可能面临什么性能问题请指导这个......!

所以请帮忙!

public class NewScheduler {

public static final Logger logger = Logger.getLogger(NewScheduler.class.getName());
static ScheduledExecutorService scheduledExecutorService;
List<ExecuterSchedulerBean> list = new ArrayList<>();
FanMonitorDao fanMonitorDao;

public static void proceed(){
    logger.info("NewScheduler || proceed || :-START");
    List<Runnable> runnableList = new ArrayList<>();

    NewScheduler scheduler = new NewScheduler();

    runnableList.add(new ActiveLinkChecker());
    runnableList.add(new SecondScheduler());
    runnableList.add(new ThirdScheduler());
    runnableList.add(new FourthScheduler());
    runnableList.add(new FifthScheduler());

    for(Runnable check : runnableList){
        try {
            scheduledExecutorService = Executors.newScheduledThreadPool(1);
            if(check instanceof ActiveLinkChecker){
                scheduler.schedulerTasks("linkChecker", check);
                ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                bean.setServiceName("linkChecker");
                bean.setScheduledExecutorService(scheduledExecutorService);
            }else if(check instanceof SecondScheduler){
                scheduler.schedulerTasks("secondChecker", check);
                ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                bean.setServiceName("secondChecker");
                bean.setScheduledExecutorService(scheduledExecutorService);
            }else if(check instanceof ThirdScheduler){
                scheduler.schedulerTasks("thirdChecker", check);
                ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                bean.setServiceName("thirdChecker");
                bean.setScheduledExecutorService(scheduledExecutorService);
            }else if(check instanceof FourthScheduler){
                scheduler.schedulerTasks("fourthChecker", check);
                ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                bean.setServiceName("fourthChecker");
                bean.setScheduledExecutorService(scheduledExecutorService);
            }else if(check instanceof FifthScheduler){
                scheduler.schedulerTasks("fifthChecker", check);
                ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                bean.setServiceName("fifthChecker");
                bean.setScheduledExecutorService(scheduledExecutorService);
            }
        } catch (SocketException e) {
            logger.info("Error in SchedularTaskServlet in Scheduling batches :-" + e);
            try {
                scheduledExecutorService = Executors.newScheduledThreadPool(1);
                if(check instanceof ActiveLinkChecker){
                    scheduler.schedulerTasks("linkChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("linkChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof SecondScheduler){
                    scheduler.schedulerTasks("secondChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("secondChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof ThirdScheduler){
                    scheduler.schedulerTasks("thirdChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("thirdChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof FourthScheduler){
                    scheduler.schedulerTasks("fourthChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("fourthChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof FifthScheduler){
                    scheduler.schedulerTasks("fifthChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("fifthChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }
            } catch (Exception ex) {
                logger.info("Error in SchedularTaskServlet in Scheduling batches :-" + ex, new Throwable());
                e.printStackTrace();
            }
            e.printStackTrace();
        } catch (SQLException e) {
            logger.info("Error in SchedularTaskServlet in Scheduling batches :-" + e);
            try {
                scheduledExecutorService = Executors.newScheduledThreadPool(1);
                if(check instanceof ActiveLinkChecker){
                    scheduler.schedulerTasks("linkChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("linkChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof SecondScheduler){
                    scheduler.schedulerTasks("secondChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("secondChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof ThirdScheduler){
                    scheduler.schedulerTasks("thirdChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("thirdChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof FourthScheduler){
                    scheduler.schedulerTasks("fourthChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("fourthChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }else if(check instanceof FifthScheduler){
                    scheduler.schedulerTasks("fifthChecker", check);
                    ExecuterSchedulerBean bean = new ExecuterSchedulerBean();
                    bean.setServiceName("fifthChecker");
                    bean.setScheduledExecutorService(scheduledExecutorService);
                }
            } catch (Exception ex) {
                logger.info("Error in SchedularTaskServlet in Scheduling batches :-" + ex, new Throwable());
                e.printStackTrace();
            }
            e.printStackTrace();
        } catch (Exception e) {
            logger.info("Error in SchedularTaskServlet in Scheduling batches :-" + e, new Throwable());
            e.printStackTrace();
        }
    }

    logger.info("NewScheduler || proceed || :-END");
}

private void schedulerTasks(String taskName, Runnable scheduler) throws SQLException, SocketException {
    logger.debug("NewScheduler || schedulerTasks || :-START");
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy kk:mm");
    Calendar cal = null;
    int weekDay = 0, weekMin = 0, weekHr = 0, runDay = 0, runHr = 0, runMin = 0, runDelay = 0;
    float runGap = 0;
    String flag = null;
    fanMonitorDao = new FanMonitorDaoImpl();
    try {
        SchedulerBean bean = fanMonitorDao.getScheduler(taskName);
        flag = (("A").equalsIgnoreCase(bean.getSchedulerStatus())?"Y":"N").trim();
        if (flag != null && flag.equalsIgnoreCase("Y")) {

            cal = Calendar.getInstance();
            weekDay = cal.get(Calendar.DAY_OF_WEEK);// get the Weekday , from 1 to 7
            weekHr = cal.get(Calendar.HOUR_OF_DAY);// get the Weekday , from 0 to 23
            weekMin = cal.get(Calendar.MINUTE);// get the Weekday , from 0 to 59
            System.out.println("Current Week Day is :->" + weekDay + ", Week Hrs:->" + weekHr + ", Week Min:->" + weekMin);
            runDay = (runDay=Integer.parseInt(bean.getSchedulerDay().trim())) == 0 ? weekDay : runDay;
            runHr = (runHr=Integer.parseInt(bean.getSchedulerHrs().trim()))== 0 ? weekHr : runHr;
            runMin = Integer.parseInt(bean.getSchedulerMin().trim());
            runGap = Float.parseFloat(bean.getSchedulerGap().trim());
            runDelay = Integer.parseInt(bean.getSchedulerDelay().trim());
            runDay = (runDay >= weekDay) ? (runDay - weekDay) : runDay + (7 - weekDay);
            runHr = (runHr >= weekHr) ? (runHr - weekHr) : runHr + (24 - weekHr);
            runMin = (runMin >= weekMin) ? (runMin - weekMin) : runMin - weekMin;
            System.out.println("Difference between current values and Property values are :-days:->" + runDay + " Hrs:->" + runHr + " Min:->" + runMin);
            cal.setTime(sdf.parse(sdf.format(new Date())));
            cal.add(Calendar.DATE, runDay);
            cal.add(Calendar.HOUR, runHr);
            cal.add(Calendar.MINUTE, runMin);
            runDay = Integer.parseInt(String.valueOf((cal.getTimeInMillis() - (sdf.parse(sdf.format(new Date()))).getTime())));
            System.out.println("Next First run time is :->" + runDay + "-->>" + runDelay * runGap * 60 * 60 * 1000);
            @SuppressWarnings("unused")
            ScheduledFuture<?> alarmFuture = scheduledExecutorService.scheduleWithFixedDelay(scheduler, (long) runDay, (long) ((long) runDelay * runGap * 60 * 60 * 1000), TimeUnit.MILLISECONDS);
        }
    } catch (Exception e) {
        logger.info("Error in SchedularTaskServlet in Scheduling batches :-" + e, new Throwable());
        e.printStackTrace();
    }
    logger.debug("NewScheduler || schedulerTasks || :-END");
}

}

2 个答案:

答案 0 :(得分:1)

使用一个ScheduledExecutorService原则上没有问题。从同一时间点开始的任务也不应成为问题。

根据任务的数量以及资源密集程度,您最终可能会耗尽线程(或CPU或IO ..),此时任务可能会延迟。但是您无法通过创建新的ScheduledExecutorService来解决这个问题。

如果您希望彼此隔离任务,那么创建多个此类服务才有意义。例如,您有一个非常重要的Task,因此您可以为此任务创建一个线程池大小为1的服务。如果现在要注意您的应用程序(包括用于所有其他任务的ScheduledExecutorService),那么Task应该始终能够在预定的时间执行。请注意,实际上线程的整体利用率会降低,因此总体时效性和吞吐量会受到影响,因为一个线程基本上是为高优先级任务保留的。

答案 1 :(得分:0)

您可以使用ScheduledThreadPoolExecutor

  

ExecutorService,可以调度命令在给定延迟后运行,或定期执行。

ScheduledExecutorService