如何确定应用程序的线程数量?

huangapple go评论86阅读模式
英文:

How to decide on number of threads for an application?

问题

我已阅读每个核心可以有两个线程的信息。那么,如果我在生产中使用三台八核服务器,这是否意味着我的应用程序只能处理48个并发请求?或者我在混淆两个不同的概念吗?

非常感谢解答。

英文:

I have read that each core can have two threads. So, if my application in prod uses three octa core servers, does that mean my application can only handle 48 concurrent requests? Or am I mixing two different things here?

Would appreciate any clarity here.

答案1

得分: 0

在Java中,您可以拥有任意数量的线程,不受您拥有多少个CPU核心的限制。即使您只有一个只有一个核心的处理器,您仍然可以编写多线程应用程序。

JVM将执行上下文切换 - 它会执行线程1一段时间,然后执行线程2一段时间,然后可能再次执行线程1,依此类推,在线程之间进行切换。这些线程之间的切换可以在几毫秒后发生,因此可以产生线程并行运行的幻觉。

在某些应用程序中,仅使用单个线程可能更快 - 因为这种上下文切换过程只会增加更多的开销。

不过,我确实在前几天编写了一个小的多线程应用程序。它大约有30个线程,这是一个多线程确实可以使应用程序更高效的用例。

我有大约30个URL需要访问并从中检索一些数据。如果我在单个线程中执行此操作,每次发出请求并等待响应时都会有等待时间(从而阻塞应用程序)。在多线程情况下,其他线程将能够在此等待期间运行。

希望这有意义。值得阅读有关Java上下文切换的更多信息。

这是有关该主题的一个很好的资源:https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

英文:

In Java, you can have as many threads as you like and you're not limited by how many CPU cores you have. I.e. Even if you only had one processor with a single core, you could still write a multi-threaded application.

The JVM will perform context switching - it will execute Thread 1 for some time, then Thread 2 for some time, then maybe Thread 1 again, and so on, switching between the threads. These switches between threads can occur after just a few milliseconds, so it can give the illusion that the threads are running in parallel.

On some applications, it is faster to just use a single thread - because this process of context switching just adds further expense.

I did actually write a small multi-threaded application the other day though. It had about 30 threads, and this was a use case where multithreading did make the app more efficient.

I had about 30 URLs that I needed to hit and retrieve some data from. If I did this in a single thread, there would be waiting time each time I made a request and waited for a response (thus, blocking the application). When multi-threading, other threads will have been able to run whilst this waiting went on.

I hope this makes sense. It'll be worth reading up on Java Context Switching for more info.

This is a good source on the topic: https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

huangapple
  • 本文由 发表于 2020年4月6日 18:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61057579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定