In the simplest case, just let your run method do its job and complete it when appropriate, something like this:
public void run() { boolean running = true; while(running) { running = doWork(); if (Thread.interrupted()) { return; } } }
Here the process stops when the doWork () method returns false. It is also a good style to interrupt a stream, especially if it should work for a long time, see this guide . In order for this to work, doWork () must return regularly. Note that you cannot restart threads as soon as the run method returns a thread that will be restored by the system.
If you need more control over threads, you can create separate Worker and ThreadManager classes.
To allow ThreadManager to exit Worker, create a mutable logical field in your Worker that is periodically checked:
public class Worker extends Thread { private volatile boolean running; public void run() { running = true; while(running) { running = doWork(); if (Thread.interrupted()) { return; } } } public void stopRunning() { running = false; } }
The employee ends when he is interrupted or when the work is completed. ThreadManager can also request a Worker stop by calling the stopRunning () method.
If your thread runs out of work, it can also call the wait () method in ThreadManager. This pauses the flow until it is notified that there is a new job to do. ThreadManager should call notify () or notifyAll () when a new job arrives (in this example, ThreadManager is used as a monitor).
With this approach, you can keep the employee simple and interested only in the performance of work. ThreadManager determines the number of threads and makes the work available to them, but it does not need to know the details of the real work. Another step is to divide the βworkβ into a separate class, which you can call βJobβ. An example of this can be found in my example with a web scanner . This can be useful for transferring new work from ThreadManager to the workflow.
UPDATE: clarification: If a thread does not do any work and it just needs to wait for some condition, do not use iteration to wait, but use either wait / notify (see the web scanner example given by me) or a simple callback when the state arises.
Adriaan koster
source share