何时/为什么应该在 Java 中使用多线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18236597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:37:17  来源:igfitidea点击:

When/Why should I use Multithread in Java?

javamultithreadingjspjakarta-ee

提问by Louis Hong

I don't know when I should use Multithread in Java development, and the logic/reason of using it. How does it help in different scenarios?

我不知道在Java开发中什么时候应该使用多线程,以及使用它的逻辑/原因。它在不同场景下有何帮助?

Scenario 1

场景一

I'm making a 2D scrolling game with enemies and a all that, think of metal slug

我正在制作一个有敌人的 2D 滚动游戏,想想金属弹头

Scenario 2

场景二

I'm making a database daemon to check multiple database content.

我正在制作一个数据库守护程序来检查多个数据库内容。

Scenario 3

场景3

I'm making a servlet for JSP, with some information fetched from the database.

我正在为 JSP 制作一个 servlet,并从数据库中获取一些信息。

Feel free to edit the scenarios to make it better.

随意编辑场景以使其更好。

In addition: Should I use multithread for game servers? Or should I not?

另外:我应该为游戏服务器使用多线程吗?或者我不应该?

采纳答案by Gray

I don't know when I should use Multithread in Java development, and the logic/reason of using it. How does it help in different scenarios?

我不知道在Java开发中什么时候应该使用多线程,以及使用它的逻辑/原因。它在不同场景下有何帮助?

You should change your program to use threads for a couple of different reasons.

出于几个不同的原因,您应该更改程序以使用线程。

  • When the program would run significantly faster and make better use of the multiple CPU/core architecture that you are running on. I use the word "significantly" because often adding threads adds a lot of complexity so a 20% speed improvement may not be worth it.

    It can be difficult, however, to determine if your program will properly make use of multiple processors so that the reworking of the program is a good investment. Only if there is a lot of processing/calculating involved will you get a speed increase. If, for example, your program is waiting for IO (disk or network reading or writing) then you might spend a lot of work splitting a program into multiple threads only to see no speed improvement.

  • When there are multiple parts of your program that should be running simultaneously. It's not that it couldn't run in one thread but to do so would be more complicated. For example, a web server has multiple request handling threads because it is easier to have each thread handle a single request even though you may not be putting a ton of load through the server so that multiple threads makes it perform faster.

  • 当程序运行速度显着加快并更好地利用您正在运行的多 CPU/核心架构时。我使用“显着”这个词是因为经常添加线程会增加很多复杂性,因此 20% 的速度提升可能不值得。

    然而,可能很难确定您的程序是否会适当地使用多个处理器,因此程序的返工是一项很好的投资。只有当涉及大量处理/计算时,您才会获得速度提升。例如,如果您的程序正在等待 IO(磁盘或网络读取或写入),那么您可能会花费大量工作将程序拆分为多个线程,结果却看不到速度提升。

  • 当您的程序有多个部分应该同时运行时。并不是它不能在一个线程中运行,而是这样做会更复杂。例如,Web 服务器有多个请求处理线程,因为即使您可能不会通过服务器加载大量负载,也可以更轻松地让每个线程处理单个请求,以便多个线程使其执行速度更快。

In addition: The same question for J2EE stuff, when should I use multithread in my servlets? Or should I not?

另外:对于 J2EE 的同样问题,我什么时候应该在我的 servlet 中使用多线程?或者我不应该?

I think the same answers above apply. In general servlets are very small tasks that are designed to return quickly so it is relatively unusual for them to fork threads. However, if there is a long-running task that a servlet needs to start but you want it to return a "Starting job" type of response then a thread will be necessary.

我认为上述相同的答案适用。一般来说,servlet 是非常小的任务,旨在快速返回,因此它们分叉线程是相对不常见的。但是,如果有一个 servlet 需要启动的长时间运行的任务,但您希望它返回“启动作业”类型的响应,则需要一个线程。

It is important to note that by the time your servlet is executed, the upstream handler is probably already making use a thread pool so you don't have to do anything.

需要注意的是,当您的 servlet 被执行时,上游处理程序可能已经在使用线程池,因此您无需执行任何操作。



Edit:

编辑:

Scenario 1 - I'm making a 2D scrolling game with enemies and a all that, think of metal slug

场景 1 - 我正在制作一个有敌人的 2D 滚动游戏,想想金属弹头

I don't have a good answer for this. Depends on whether there is a lot of rendering going on and it depends on what toolkits you are using.

对此我没有很好的答案。取决于是否有大量渲染正在进行,也取决于您使用的工具包。

Scenario 2 - I'm making a database daemon to check multiple database content.

场景 2 - 我正在制作一个数据库守护进程来检查多个数据库内容。

Chances are you are going to be database IO bound so multiple threads may not give you anything. Then again, if you have long running queries, you might get some improvement if short queries could be executing in parallel on other threads. This also depends on how your database handles multiple connections.

您可能会受到数据库 IO 限制,因此多个线程可能不会给您任何东西。再说一次,如果您有长时间运行的查询,如果可以在其他线程上并行执行短查询,您可能会得到一些改进。这也取决于您的数据库如何处理多个连接。

Scenario 3 - I'm making a servlet for JSP, with some information fetched from the database.

场景 3 - 我正在为 JSP 制作一个 servlet,并从数据库中获取一些信息。

If the response has to wait for the information to be fetched then there is no reason to do this in another thread. However, as I mentioned above, if the servlet is trying to fork some sort of database transaction that runs in the background then you should use a thread.

如果响应必须等待获取信息,则没有理由在另一个线程中执行此操作。但是,正如我上面提到的,如果 servlet 试图派生某种在后台运行的数据库事务,那么您应该使用线程。

Again, most servlet containers already are running inside a thread pool.

同样,大多数 servlet 容器已经在线程池中运行。

回答by Jatin

Use Multi-Threading when you can think something can be parallelized or can be made asynchronous.

当您认为某些事情可以并行化或异步化时,请使用多线程。

Parallelized For example: While building Web-crawlers, you can have parallel threads which browse through different pages etc. This might also mean to better utilize resources (CPU, I/O etc)

并行化例如:在构建网络爬虫时,您可以拥有浏览不同页面等的并行线程。这也可能意味着更好地利用资源(CPU、I/O 等)

Asynchronous in the sense, in the case of produce-consumer where you have a block of code producing stuff and the rest consuming it.

在某种意义上是异步的,在生产消费者的情况下,您有一个代码块生产东西,其余的则消费它。

回答by Sajal Dutta

I don't know when I should use Multithread in Java development

我不知道我什么时候应该在 Java 开发中使用多线程

-Then you should not. Also, if you can avoid it, by all means do so.

- 那你不应该。此外,如果您可以避免它,请务必这样做。

When: An example: If you need to fetch market share values of different stocks from multiple sites/resources exactly at the same time to update different broker systems, you may need to as a single thread will have to get from one site first before it tries getting from the next one.

什么时候:一个例子:如果您需要完全同时从多个站点/资源获取不同股票的市场份额值以更新不同的经纪系统,您可能需要作为单个线程在它之前首先从一个站点获取尝试从下一个。

Based from your edit in your question-

根据您在问题中的编辑-

Secnario 1: I'm making a 2D scrolling game with enemies and a all that, think of metal slug

Secnario 1:我正在制作一个有敌人的 2D 滚动游戏,想想金属弹头

Yes you can. An example would be do the loading of resources in one thread while displaying a "Loading..." animation on the screen in another thread.

是的你可以。一个例子是在一个线程中加载资源,同时在另一个线程的屏幕上显示“正在加载...”动画。

回答by Pacane

It's not really like you once learn multithreading, then you use it all the time everywhere. You use multithreading when you need it.

不像你曾经学习过多线程,然后你到处都在使用它。在需要时使用多线程。

For example you have a long task to do, and you don't want to lock the UI, you can do the task on another thread while your UI still works well. That would be one scenario.

例如,您有一个很长的任务要做,并且您不想锁定 UI,您可以在您的 UI 仍然运行良好的同时在另一个线程上执行该任务。那将是一种情况。

Another would be to calculate something complex that can be done in many independent steps, then it could be done in parallel using multithreading.

另一种方法是计算可以在许多独立步骤中完成的复杂事情,然后可以使用多线程并行完成。

回答by Abstract

Let's say that you have an application that's in charge of downloading a file, if you don't use multiple threads, all other instructions would wait until the file finish to download. Swing for example use a special thread in order to display his gui, so you should take a look to thistutorial and read a little bit of concurrency

假设您有一个负责下载文件的应用程序,如果您不使用多线程,则所有其他指令都将等到文件完成下载。例如 Swing 使用一个特殊的线程来显示他的 gui,所以你应该看看这个教程并阅读一点点并发