Is multithreading faster than single thread?

我只是一个虾纸丫 提交于 2019-12-01 07:34:23
Ravindra babu

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.

  1. Number of threads
  2. CPU cores
  3. Thread creation cost and context switching ( may work against multi-threading)
  4. Data structures
  5. Mutability of data ( may work against multi-threading)
  6. Shared access/ Concurrency of data structure ( may work against multi-threading)
  7. Type of application : CPU bound or IO Bound

Multi threading will provide excellent results if your application is

  1. Less CPU bound, less IO Bound ( But still multi-threading can be used for these applications)

  2. 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

  1. There is absolutely a cost to creating additional threads. You should have a non-trivial amount of work needed before spinning up a new thread.
  2. I assume this means you have a quad-core CPU. The optimal number of threads actually depends on the workload, if threads are waiting for whatever reason they may be able to context switch to a another thread and you may see a benefit with a number of threads greater than the number of physical cores.
  3. I don't understand the question.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!