Search code examples
javamultithreadingconcurrencycpujava-threads

Confused about concurrency and Java threads


After reading about concurrency with Java threads, I got a bit confused. Some have claimed (they might be wrong) that Java threads are executed concurrently?

If you have 4 CPU's that can do multithreading (can handle 8 threads), how is it possible that when you create 30 threads in your Java code that these are all executed concurrently (at the same time)? Only 4 can be run concurrently so far I know and the other 4 threads are waiting for execution and 22 are in the queue pool. Am I missing something or am I understanding the term concurrently wrong?


Solution

  • Its simple - in your scenario 30 threads are started but only 4 of them are executed at the same time (at given instant). Threads are executed litle piece by piece. Pieces from any thread can be executed but only 4 at given time.

    If you would have 2 construction teams (Cores) that would built 10 houses (Threads) at once, but every house would be build only for 4 hours a day by single team (thread scheduling), you would still say that 10 houses are built concurrently, but not necessarily at exact same time (as only 2 of them will be build at exact same moment).

    The same happens with threads in OS and JVM.