Lenny
Lenny

Reputation: 21

Does multi cores machines helps in fast processing with Multithreading?

I'm getting confused with multiple threads execution within in multiple cores of a machine.

For example, I've a method which is bulding a 100 story building.

synchronized buildingStories(){

}

To complete building faster, I decide to use 4 workers (threads). Lets say when T1 will build a floor1 and T2 will build floor2 and so on.

So once T1 acquired a lock on buildingStories , T2 wont be able to acquire lock and do his build until T1 release it. Even machine is mutli core and other threads or workers have to be in queue until shared resource is free, how multi threading increasing the performance ? At the end Thread have to wait until its turn come and run to core to process it.

Its very naive quesion, but suggestion would be appreciated to understand.

Upvotes: 0

Views: 135

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83597

You are correct. If two threads lock the same object, then one of the threads will block, which doesn't help with performance. If on the other hand, the two threads can run completely independently of each other, then there is a huge performance gain.

Upvotes: 1

Related Questions