如何强制ExecutorService立即运行?

时间:2016-11-24 13:59:52

标签: java threadpool java-threads

我有一个ExecutorService,我想立即运行messageConsumer线程。当我在代码下面运行它时会记录"提交已完成"但经过近4-5分钟的消息消费者线程开始。

我想强制这个线程立即运行。

BlockingQueue<Runnable> threadPoolQueue = new LinkedBlockingQueue<>();
ThreadPoolExecutor executorService = new ThreadPoolExecutor(50, 50, 30000, TimeUnit.MILLISECONDS, threadPoolQueue, new CustomThreadFactory("consumers"));
executorService.allowCoreThreadTimeOut(true);

MessageConsumer messageConsumer = new MessageConsumer(chargingService, messageSender);
executorService.submit(messageConsumer);
logger.debug("submit completed.");

这是MessageConsumer;

public class MessageConsumer implements Runnable {
   public void run() {
      logger.debug("MessageConsumer starting...");
   }
}

编辑:我顺便使用java 7。

public class CustomThreadFactory implements ThreadFactory {

 private static final AtomicInteger poolNumber = new AtomicInteger(1);
 private final ThreadGroup group;
 private final AtomicInteger threadNumber = new AtomicInteger(1);
 private final String namePrefix;

 public CustomThreadFactory(String groupName) {
    SecurityManager s = System.getSecurityManager();
    group = (s != null) ? s.getThreadGroup()
            : Thread.currentThread().getThreadGroup();
    namePrefix = groupName + "-thread";
 }

 @Override
 public Thread newThread(Runnable r) {
    Thread t = new Thread(group, r, namePrefix + "-" + threadNumber.getAndIncrement(), 0);
    if (t.isDaemon()) {
        t.setDaemon(false);
    }
    if (t.getPriority() != Thread.NORM_PRIORITY) {
        t.setPriority(Thread.NORM_PRIORITY);
    }
    return t;
 }
}

0 个答案:

没有答案