本文介绍了如果当前线程处于休眠状态,ThreadPoolExecutor是否会产生新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是对这个问题.

本质上,我正在做的是声明只有一个线程的ThreadPoolExecutor.我重写了beforeExecute()方法以使自己进入睡眠状态,以便我的每个任务之间的执行都有一定的延迟.基本上,这是为了将CPU分配给其他线程,因为我的线程有点不正常.

Essentially what I am doing is declaring a ThreadPoolExecutor with just one thread. I am overriding the beforeExecute() method to put a sleep so that each of my tasks are executed with some delay among themselves. This is basically to give away the CPU to other threads since my thread is kind of thrashing.

所以预期的行为是:

对于ThreadPoolExecutor中的每个新任务,它都会在执行任务之前调用before execute函数,因此在执行任务之前它会休眠20秒钟.

For each new task in the ThreadPoolExecutor, it calls the before execute function before executing the task and hence it sleeps for say 20s before it executes the task.

但是我看到的是这样:

对于提交的每个新任务:

For each new task submitted:

  1. 它执行任务
  2. 调用beforeExecute方法
  3. 睡20秒
  4. 重新执行任务!

1.&的顺序. 2.一直都不一样.

The order of 1. & 2. is not the same all the time.

这是我的问题:

  1. 似乎有一个新线程在睡眠之后/期间进入,并在实际线程正在睡眠时继续执行我的任务.
    那么,ThreadPoolExecutor会在现有线程休眠后立即产生一个新线程吗(认为该线程已终止)?我试着把keepAliveTime> sleeptime ..以便在上述断言为真的情况下..它至少等待了比休眠时间更长的时间来生成一个新线程... [希望在此期间,休眠线程将苏醒,并且ThreadPoolExecutor会放弃生成新线程的想法
  2. 即使它确实产生了一个新线程并立即执行我的任务,为什么在睡眠线程唤醒后仍要重新执行该任务!
  3. 我在这里想念什么吗?还有其他方法可以调试这种情况吗?
  1. It is appearing that a new thread comes in after/during sleeping and goes ahead and executes my task right away while the actual thread is sleeping.
    So does the ThreadPoolExecutor spawn a new thread as soon as an existing thread sleeps [thinking that the thread is terminated]??I tried to put the keepAliveTime > sleeptime ..so that in case the above assertion is true .. it atleast waits for more than sleep time to spawn a new thread ...[hoping in the mean time the sleeping thread would be awake and the ThreadPoolExecutor would dump the idea of spawning a new thread
  2. Even if it does spawn a new thread and execute my task right away, why would the task be re-executed after the sleeping thread wakes up !! Shouldn't the task be taken out of task Queue before that ??
  3. Am I missing something here ? Any other way to debug this scenario ?

=>我正在考虑执行所需任务(而不是解决难题)的另一种方法是,将可运行对象与另一个可运行对象包装在一起,并在调用内部可运行对象之前将外部可运行对象睡眠.

=> An alternative method I was thinking to do the desired task [and not solve the peoblem] was to wrap the runnable with one more runnable and sleep the outer runnable before calling the inner one.

推荐答案

我认为您正在寻找的是 ScheduledExecutorService

I think what you're looking for is a ScheduledExecutorService

据我对您的问题的了解,scheduleAtFixedRate(...)应该可以解决此问题:

From what I understand of your question, scheduleAtFixedRate(...) should do the deal:

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

这篇关于如果当前线程处于休眠状态,ThreadPoolExecutor是否会产生新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:53