001package horstmann.ch09_animation2; 002import java.util.Comparator; 003import java.util.concurrent.BlockingQueue; 004 005/** 006 This runnable executes a sort algorithm. 007 When two elements are compared, the algorithm 008 pauses and updates a panel. 009 */ 010public class Sorter implements Runnable 011{ 012 public Sorter(Double[] values, ArrayComponent panel, BlockingQueue<String> queue) 013 { 014 this.values = values; 015 this.panel = panel; 016 this.queue = queue; 017 } 018 019 public void run() 020 { 021 Comparator<Double> comp = (d1, d2) -> { 022 try 023 { 024 String command = queue.take(); 025 if (command.equals("Run")) 026 { 027 Thread.sleep(DELAY); 028 if (!"Step".equals(queue.peek())) 029 queue.add("Run"); 030 } 031 } 032 catch (InterruptedException exception) 033 { 034 Thread.currentThread().interrupt(); 035 } 036 panel.setValues(values, d1, d2); 037 return d1.compareTo(d2); 038 }; 039 MergeSorter.sort(values, comp); 040 panel.setValues(values, null, null); 041 } 042 043 private Double[] values; 044 private ArrayComponent panel; 045 private BlockingQueue<String> queue; 046 private static final int DELAY = 100; 047}