#476 Execution Time of Exercises in ThreadPoolExecutor
How long will the program take on a machine with 1 CPU and no HT?
static void sleepOneSecond() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
try (var pool = new ThreadPoolExecutor(
/*core pool size*/ 2,
/*maximum pool size*/ 10,
/*keepAliveTime value and unit*/ 30,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(10))) {
var start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
pool.execute(Pool::sleepOneSecond);
// what about this?
/*
var t = new Thread(Pool::sleepOneSecond);
t.setDaemon(true);
pool.execute(t);
*/
}
Runtime.getRuntime().addShutdownHook(new Thread(() ->
log.info("Time taken: " + (System.currentTimeMillis() - start))));
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor