Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 487
David Avatar asked Jun 06 '10 17:06

David


People also ask

Can thread be reused?

Thread Pool: Reusing Existing Thread To Save MemoryThread Pool Pattern stands for reusing existing threads and running all new instructions without allocation of new threads. The thread pool controls the number of running threads and is widely used in production. This pattern has implementations in Java: Executors.

How do you rerun a thread?

Calling the start() function on a terminated thread will result in a RuntimeError indicating that threads can only be started once. Instead, to restart a thread in Python, you must create a new instance of the thread with the same configuration and then call the start() function.

Can we restart a thread?

Once a thread enters dead state it cannot be restarted.

How do I run a thread from one after another?

We can use use join() method of thread class. To ensure three threads execute you need to start the last one first e.g. T3 and then call join methods in reverse order e.g. T3 calls T2. join, and T2 calls T1.


2 Answers

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.

like image 91
BalusC Avatar answered Sep 22 '22 04:09

BalusC


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.

like image 34
Omry Yadan Avatar answered Sep 26 '22 04:09

Omry Yadan