Is Java: executorservice less efficient than manual thread execution?
I have a multithreaded application When using thread When start () starts threads manually, each concurrent thread uses exactly 25% of the CPU (or exactly one core - this is on a quad core machine) Therefore, if I run two threads, the CPU utilization is exactly 50%
However, when using executorservice to run a thread, it seems that a "ghost" thread consumes CPU resources! One thread uses 50% instead of 25%, two threads use 75%, etc
Could this be some kind of artifact of Windows Task Manager?
The excutor service code is
ExecutorService executor = Executors.newFixedThreadPool(threadAmount); for (int i = 1; i < 50; i++) { Runnable worker = new ActualThread(i); executor.execute(worker); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads");
And thread The start () code is:
ActualThread one= new ActualThread(2,3); ActualThread two= new ActualThread(3,4); ... Thread threadOne = new Thread(one); Thread threadTtwo = new Thread(two); ... threadOne.start(); threadTwo.start(); ...
Solution
Here's your question:
while (!executor.isTerminated()) { }
Your "main" method is to let the CPU do nothing Please use invokeall() instead. Your thread will block without busy waiting
final ExecutorService executor = Executors.newFixedThreadPool(threadAmount); final List<Callable<Object>> tasks = new ArrayList<Callable<Object>>(); for (int i = 1; i < 50; i++) { tasks.add(Executors.callable(new ActualThread(i))); } executor.invokeAll(tasks); executor.shutdown(); // not really necessary if the executor goes out of scope. System.out.println("Finished all threads");
Since invokeall() requires a callable collection, please note the auxiliary method executors callable(). You can actually use it to get the future collection of tasks, which is very useful if the task actually generates the output you want