I have a Java thread with a run method that computes a lot of things. You can think of it as a series of mathematical statements as follows. Please note that in each calculation other methods may be used, which, in turn, may have additional cycles, etc.
public void run() { [computation 1 goes here here that takes a few seconds] [computation 2 goes here that takes a few seconds] .... [computation 30 goes here that takes a few seconds] }
There is a GUI that outputs the output of these statements as they are output, and I would like the user to say βStopβ whenever he wants. Here are two methods that I thought about
Method 1: Lots of Boolean Checks [LOOKS TERRIBLE]
private boolean stop; public void run() { if(!stop) [computation 1 goes here here that takes a few seconds] if(!stop) [computation 2 goes here that takes a few seconds] .... if(!stop) [computation 30 goes here that takes a few seconds] }
In this method, when the stop flag is set to true, the calculations are completed. Notice how stupid it is with 30 if statements. It is important to note that the critical question is how often to establish these conditions. Note that the calculations on each line are not necessarily one line. Taken to the extreme, does EVERY line in the run() method deserve to be called if(!stop) above it? It doesn't look like a good design.
Method 2: Generalize Computing [CANNOT DO IT]
pirivate boolean stop; public void run() { for(int i = 0; i < computationsN && !stop; i++) { computuations.get(i).compute(); }
I assume that this method will be proposed, so I would just like to say that this is not possible in my case, given the explicit change in the lines, which I call "calculations" for simplicity. I usually did this for threads, which are the base while loops, and it works great for such purposes. But not in this case, when the run() method is just a huge variable code method.
Any other solutions? It seems like this should be a universal problem. Thanks in advance!
java multithreading
Codeguy
source share