I want to check whether multithreading is faster than single thread,then I make a demo here:
public class ThreadSpeedTest {
/**
* @param args
*
1.SecondThreadStart cost more time than singleThreadStart, is it because the cost of creating thread?
Certainly there is overhead with creation of thread.
2.The cpu number is 4, despite the cost of creating thread, so using thread number more than 4 will slower than using four threads?
If the threads are finishing very quickly ( Not IO bound and CPU bound), you can have good results even if number of threads are more than number of CPU cores.
3.If I want to do something cost much time, using four threads to do is best?
You can use advanced java concurrent classes ( newWorkStealingPool
of Executors
)
Refer to this SE question:
Java's Fork/Join vs ExecutorService - when to use which?
In General:
Multi threading may improve throughput of the application by using more CPU power.
it depends on a lot of factors.
Multi threading will provide excellent results if your application is
Less CPU bound, less IO Bound ( But still multi-threading can be used for these applications)
No shared data
If not, the performance depends on above factors and throughput will vary between single threaded application and multi-threading application.
Some good SE questions:
https://softwareengineering.stackexchange.com/questions/97615/what-can-multiple-threads-do-that-a-single-thread-cannot
Does multithreading always yield better performance than single threading?
Why single thread is faster than multithreading in Java?
Good articles:
thetechsolo.wordpress.com article
java-performance article