IntervalGuesser

We discussed the different Java language elements and JDK classes that are all available to implement parallel algorithms. Now, we will see how to use these approaches to implement the parallel guesser for the Masterrmind game.

The class that performs the creation of the guesses is named IntervalGuesser. It creates the guesses between a start and an end guess and sends them to a BlockingQueue. The class implements Runnable so it can run in a separate Thread. The purist implementation will separate the Runnable functionality from the interval guessing, but as the whole class is hardly more than 50 lines, it is forgivable sin implementing the two functionalities in a single class.

public class IntervalGuesser extends UniqueGuesser implements Runnable { 
private final Guess start;
private final Guess end;
private Guess lastGuess;
private final BlockingQueue<Guess> guessQueue;

public IntervalGuesser(Table table, Guess start, Guess end, BlockingQueue<Guess> guessQueue) {
super(table);
this.start = start; this.end = end;
this.lastGuess = start;
this.guessQueue = guessQueue;
nextGuess = start;
}
@Override
public void run() {
Guess guess = guess();
try {
while (guess != Guess.none) {
guessQueue.put(guess);
guess = guess();
}
} catch (InterruptedException ignored) {
}
}
@Override
protected Guess nextGuess() {
Guess guess;
guess = super.nextGuess();
if (guess.equals(end)) {
guess = Guess.none;
}
lastGuess = guess;
return guess;
}

public String toString() {
return "[" + start + "," + end + "]";
}
}

The implementation is very simple as most of the functionality is already implemented in the abstract Guesser class. The more interesting code is the one that invoked the IntervalGuesser.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.70.247