javamultithreading

Does Java access all threads automatically?


I'm not very knowledgeable on multi-threading in Java. But after a brief search online I saw people creating classes implementing the Thread class and starting these new thread objects, or something along those lines. I also saw a higher level concurrency library.

At the moment I have written a very simple program and have it running with absolutely nothing optimised for multi-threaded processers.

However, when I run the program from the terminal and check my Activity Monitor (Task manager) I notice 100% of CPU is being used. Hence, all threads must are being accessed. Is this right? Does this mean there is no reason to implement threading in the code I write?

Will my program use all CPU threads without me telling it to do so?

I remember writing a C++ program months back and this was not the case. It was showing 50% CPU usage for each program I ran.

Here is my Activity Monitor:

enter image description here


Solution

  • Hence, all threads must are being accessed. Is this right? Does this mean there is no reason to implement threading in the code I write?

    A java program requires a Thread to run - for a program launched via the main method this is the main thread launched by the JRE. If all the computation is within this method, it is running on a single thread (and in theory on a single CPU). If the process/computation can be parallelized, there is reason to do so, and there is sufficient CPU available then launching more threads can speed up the process (within reason relative to the number of CPU's)

    Will my program use all CPU threads without me telling it to do so?

    The OS will distribute to the CPU's. This being said, a thread is a serial computation...meaning that it cannot be distributed to two CPU's at the same time. As a result, running a single java thread (that does not sleep or wait) on a 2 CPU computer should result in 50% total CPU usage by the application (on a 4 CPU this goes down to 25%, and so on...)