简体   繁体   English

如何在Java中重用线程?

[英]How to re-use a thread in Java?

I am a building a console Sudoku Solver where the main objective is raw speed. 我正在构建控制台Sudoku Solver,其主要目标是原始速度。

I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. 我现在有一个ManagerThread,它启动WorkerThreads来计算每个单元的neibhbors。 So one WorkerThread is started for each cell right now. 因此,现在为每个单元启动一个WorkerThread。 How can I re-use an existing thread that has completed its work? 如何重用已完成工作的现有线程?

The Thread Pool Pattern seems to be the solution, but I don't understand what to do to prevent the thread from dying once its job has been completed. 线程池模式似乎是解决方案,但是我不知道该如何防止线程在其工作完成后死亡。

ps : I do not expect to gain much performance for this particular task, just want to experiment how multi-threading works before applying it to the more complex parts of the code. ps:我并不希望此特定任务获得太多性能,而只是想在将多线程应用于代码的更复杂部分之前对其进行实验。

Thanks 谢谢

Have a look at the Java SE provided java.util.concurrent API. 看看Java SE提供的java.util.concurrent API。 You can create a threadpool using Executors#newFixedThreadPool() and you can submit tasks using the ExecutorService methods. 您可以使用Executors#newFixedThreadPool()创建Executors#newFixedThreadPool() ,也可以使用ExecutorService方法提交任务。 No need to reinvent your own threadpool. 无需重新发明自己的线程池。 Also see the Sun tutorial on the subject . 另请参阅有关该主题Sun教程

when using a thread pool (java.util.concurrent) , you never actually initialized a thread - but rather pass Runnables to the thread pool. 使用线程池(java.util.concurrent)时,您从未真正初始化线程-而是将Runnables传递给线程池。 you don't need to worry about the thread life-cycle, just do whatever work you need to do in the runnable and let it exit when it's done. 您不必担心线程的生命周期,只需在可运行对象中执行所需的任何工作,并在完成时退出即可。

Well, if I had to code this logic my self instead of using a package like Quartz from OpenSymphony, I would do the following: I'd have a WorkerThread which extends Thread. 好吧,如果我必须自己编写这种逻辑,而不是使用OpenSymphony的Quartz这样的软件包,则可以执行以下操作:我将拥有一个扩展线程的WorkerThread。 This class will also have private property called runnable which is Runnable. 此类还将具有称为runnable的私有属性,即Runnable。 This property will hold a reference to the code you'd like to execute. 此属性将包含对您要执行的代码的引用。 Have a public setter for it. 有一个公共的二传手。 The main thread code will start by running the runnable you initialized it with and then switch to a wait state. 主线程代码将通过运行您使用其初始化的可运行对象开始,然后切换到等待状态。 Before doing that, it will mark to the pool manager that it has finished and it can be returned to the pool. 在此之前,它将向池管理器标记它已完成,并且可以将其返回到池中。 Next time you need a thread, you pick one from the pool, call setRunnable which sets the property runnable, and then wakes up the thread. 下次需要线程时,请从池中选择一个线程,调用setRunnable来设置属性runnable,然后唤醒线程。 It will spawn back to work, enter the infinite loop: execute and runnable and go back to wait state. 它将恢复工作,进入无限循环:执行并运行,然后返回等待状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM