How to re-use a thread in Java?
I am a building a console Sudoku Solver where the main objective is raw speed.
开发者_如何转开发I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. So one WorkerThread is started for each cell right now. 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.
Thanks
Have a look at the Java SE provided java.util.concurrent
API. You can create a threadpool using Executors#newFixedThreadPool()
and you can submit tasks using the ExecutorService
methods. No need to reinvent your own threadpool. Also see the Sun tutorial on the subject.
when using a thread pool (java.util.concurrent) , you never actually initialized a thread - but rather pass Runnables to the thread pool. 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.
Have a look into using CyclicBarrier synchro: http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html
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. This class will also have private property called runnable which is 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. It will spawn back to work, enter the infinite loop: execute and runnable and go back to wait state.
精彩评论