Java: ExecutorService is less efficient than manual thread execution?

I have a multithreaded application. When using Thread.start () to manually start threads, each parallel thread uses exactly 25% of the CPU (or exactly one core - this is on a quad-core processor). Therefore, if I run two threads, then the processor utilization is exactly 50%.

However, when using the ExecutorService to start threads, it seems that one 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 the Windows task manager?

Excutor Service Code

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.start () code:

 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(); ... 
+6
java performance multithreading
source share
1 answer

Here is your problem:

 while (!executor.isTerminated()) { } 

Your "main" method rotates the processor without doing anything. Use invokeAll() , and your thread will block without a lively wait.

 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() wants the Callable collection, note the use of the auxiliary method Executors.callable() . In fact, you can use this to get a Future collection for tasks, which is useful if tasks actually produce what you want as output.

+16
source share

All Articles