Home >Java >javaTutorial >Java multithreading costs
Converting from single-threaded to multi-threaded provides more than just benefits. It also comes at a price. Don't use multithreading in your application just because you can. You should have a good idea of what you will gain by doing this, and the benefits will outweigh the costs. When in doubt, try testing to measure an application's performance or responsiveness instead of just guessing.
More complex design
Although some parts of multi-threading are simpler than single-threading, other parts are more complex. Accessing shared data through code executing from multiple threads requires special attention. Thread interaction is always simple in principle. Errors that arise from incorrect thread synchronization are difficult to detect, occur, and fix.
Context switching overhead
When a CPU switches from one thread to another, the CPU needs to save the local data of the current thread. , program pointer and other information, as well as loading the local data of the next thread, the program pointer to execute. This switch is called "context switch". The CPU switches from the context of executing one thread to the context of executing another thread.
Context switching is not cheap. You don't want to switch between threads any longer than necessary.
Increase resource consumption
A thread requires some resources of the computer in order to run. In addition, a thread of the CPU requires some memory to maintain its local stack. Some resources may also be occupied within the operating system management thread. Try creating a program with 100 threads that does nothing but wait, and see how much memory it consumes when running.
The above is the content of Java multi-threading cost. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!