将新任务添加到ThreadPoolExecutor的已运行队列中

时间:2018-06-28 13:20:29

标签: java multithreading threadpool blockingqueue

在我的应用程序中,有带有BlockingQueue的ThreadPoolExecuter 现在的情况是,我们从数据库中获取一些任务,并将其交给ThreadPoolExecuter 它以允许的threadCount开始执行线程,并将其余线程保留在BlockingQueue中。

对于新要求,
我需要从BlockingQueue中删除已经运行的任务或动态删除BlockingQueue
并在执行过程中添加具有不同任务的新队列或具有正在运行的队列的新任务(如果我从数据库中获得优先任务)

只需简单的步骤
步骤1:如果我从数据库获得优先级任务,则动态地从BlockingQueue中删除正在运行的任务
步骤2:在执行时将新任务添加到BlockingQueue 这样ThreadPoolExecuter应该执行新添加的任务

我当前的代码段:

    //RejectedExecutionHandler implementation
    RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
    //Get the ThreadFactory implementation to use
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    int blockingQueue = positions > threadCount ? positions - threadCount : 1;
    logger.info("BlockingQueue size: " + blockingQueue);
    //creating the ThreadPoolExecutor
    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(blockingQueue); 
    AThreadPoolExecutor executorPool = new AThreadPoolExecutor(1, threadCount, 10, TimeUnit.SECONDS, queue, threadFactory, rejectionHandler);

    //start the monitoring thread
    MonitorRoutingThread monitor = new MonitorRoutingThread(executorPool, 10, "taskJob");
    Thread monitorThread = new Thread(monitor);
    monitorThread.start();

    //submit work to the thread pool
    logger.info("Create taskJob threads");
    if(pList != null) {
        for(String prop : pList) {
            executorPool.execute(new GThread(prop));
        }
    }

    while(executorPool.getActiveCount() != 0) {
        try {
            Thread.sleep(10000); // 10 sec wait
        } catch (InterruptedException e) {
            logger.error("Thread sleeping: ", e);
        }
    }
    //shut down the pool
    executorPool.shutdown();
    //shut down the monitor thread
    try {
        Thread.sleep(5000); 
    } catch (InterruptedException e) {
        logger.error("Error while thread sleeping: ", e);
    }
    monitor.shutdown();
    logger.info("Number rejected processes: " + rejectionHandler.getCount());

任何建议都值得欢迎和赞赏
请让我知道,如果不清楚的话,请获取更多信息

预先谢谢你

0 个答案:

没有答案