If the threads are still execute()
-ing they won't stop since you set their state to IDLE just afterwards, ignoring the previous value. And even adding a check before status = IDLE
won't work in all cases.
I suggest to use an AtomicInteger
instead of a volatile int and use its compareAndSet
method, i.e.:
while (status.get() == RUNNING) {
try {
execute(); //<-- very intensive
if (!status.compareAndSet(RUNNING, IDLE))
break;
} catch (Exception e) {
logger.info("An exception occured in thread with ID : " + id);
e.printStackTrace();
} finally {
try {
Thread.sleep(DYNAMIC_VALUE);
} catch (InterruptedException e) {}
if (!status.compareAndSet(IDLE, RUNNING))
break;
}
}
You should also interrupt the thread after setting its status to STOPPED to interrupt the sleep
if applicable.