I'm currently working on a shortest path algorithm (very basic), and to speed things up i wanted to make it bi-directional (the algorithm will start scanning in 2 directions instead of one). To accomplish this, i was thinking of using Threads to run 2 scanners at the same time.
Now when one of the Scanners meats the other one, a match is found (the shortest path must be within the scanned area), and both threads need to stop running. To prevent my application from stopping to run when both Threads are started, i placed them in an infinite loop, and check if one of the scanners have found a match yet.
After some reading on the Java Tutorial, i discovered something named Guarded Blocks. I don't quite understand how it works yet, but i think this is exactly what i need. In the description they speek of unnecessary use of memory and wasted processor time when using a neverending loop (or at least till the condition fails).
I tried working with those Guarded Blocks, but it doesn't seem to work (no doubt i'm doing something wrong). Here's a basic example of what i have now, and what needs to be changed to those Guarded Blocks if possible:
Java Code:
public class ShortestPath{
private Scanner start = new Scanner();
private Scanner end = new Scanner();
public boolean search() throws NoPathFoundException {
start.start();
end.start();
while (!end.hasMatch() && !start.hasMatch()) {
// waste some processing time
}
return end.hasMatch() || start.hasMatch();
}
public class Scanner
extends Thread {
private boolean match = false;
public void run() {
while(true){
// loop over all entries of the map to see what the shortest path is
// checks in the scanned list of the second Scanner to see if the current entry of the map is allready in there, if so a match is found
// if match:
setMatch(true);
}
}
public boolean hasMatch() {
return match;
}
}
If you look at
this article at the Java Tutorials, you'll see that there must be a better way to do what i want. I just don't understand how it works exactly.
I tried letting my ShortestPath class wait() in the while(!end.hasMatch() && !start.hasMatch()) loop, and then trigger a notifyAll event in the Scanner (when a match was found), but it didn't unlock the ShortestPath class, leaving it in an infinite loop
Many thanks if someone can help me understand the concept of Guarded Blocks