01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
package horstmann.ch09_animation2;
import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
/**
This runnable executes a sort algorithm.
When two elements are compared, the algorithm
pauses and updates a panel.
*/
public class Sorter implements Runnable
{
public Sorter(Double[] values, ArrayComponent panel, BlockingQueue<String> queue)
{
this.values = values;
this.panel = panel;
this.queue = queue;
}
public void run()
{
Comparator<Double> comp = (d1, d2) -> {
try
{
String command = queue.take();
if (command.equals("Run"))
{
Thread.sleep(DELAY);
if (!"Step".equals(queue.peek()))
queue.add("Run");
}
}
catch (InterruptedException exception)
{
Thread.currentThread().interrupt();
}
panel.setValues(values, d1, d2);
return d1.compareTo(d2);
};
MergeSorter.sort(values, comp);
panel.setValues(values, null, null);
}
private Double[] values;
private ArrayComponent panel;
private BlockingQueue<String> queue;
private static final int DELAY = 100;
}
|