1  import java.util.*;
  2  import java.util.concurrent.*;
  3  
  4  /**
  5     This runnable executes a sort algorithm.
  6     When two elements are compared, the algorithm
  7     pauses and updates a panel.
  8  */
  9  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 = (d1, d2) ->
 21           {
 22              try
 23              {
 24                 if (queue.contains("Run"))
 25                    Thread.sleep(DELAY);
 26                 else
 27                 {
 28                    String command = queue.take();
 29                    if (command.equals("Run"))
 30                       queue.add(command);
 31                 }
 32              }
 33              catch (InterruptedException exception)
 34              {
 35                 Thread.currentThread().interrupt();
 36              }
 37              panel.setValues(values, d1, d2);
 38              return d1.compareTo(d2);
 39           };
 40        MergeSorter.sort(values, comp);
 41        panel.setValues(values, null, null);
 42     }
 43  
 44     private Double[] values;
 45     private ArrayComponent panel;
 46     private BlockingQueue<String> queue;
 47     private static final int DELAY = 100;
 48  }