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