-1

I'm working on an interactive sorting application in JavaFx:

  • The numbers are represented by rectangles
  • Every time two numbers are swapped the rectangles are swapped(using timeline - animation)

This is one of the sorting algorithms:

 public class BubbleSort implements SortAlgorithm {
private volatile Boolean swaping;

public void sort(double[] array, CompareFunction compareFunction, Model model, Controller controller) {
    Boolean ord;
    int i;
    double aux;

    swaping = false;

    do {
        ord = true;

        for (i = 0; i < array.length - 1; i++) {
            if (compareFunction.compare(array[i], array[i + 1]) == false) {
                while (swaping);

                swaping = true;

                aux = array[i];
                array[i] = array[i + 1];
                array[i + 1] = aux;
                ord = false;

                controller.swapRectangles(model.getRectangles().get(i), model.getRectangles().get(i + 1), this);
            }
        }
    } while (ord == false);
}

public void setSwaping(Boolean swaping) {
    this.swaping = swaping;
}

}

This is the prototype of the swapRectangles method:

public void swapRectangles(final Rectangle rectangle1, final Rectangle rectangle2,    final BubbleSort bubbleSort)

And when timeline ends I udpate "swaping" value:

        timeline2.setOnFinished(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            setRectangleFill(rectangle2, Color.BLACK);
            rectangle2.setX(rectangle1X);
            bubbleSort.setSwaping(false);
        }
    });

The problem is that the "swaping" variable is never updating(the setSwaping method is never called).

Do you know why?

4

2 回答 2

3
  1. 运行while(swaping);对处理器施加了很大的压力,您正在消耗它的所有能量并将其交给“无所事事”循环。为了解决这个问题,要么在里面添加 sleep:while(swaping) Thread.sleep(100);要么使用更方便的同步机制,如Semaphore

  2. 此外,如果您sort在 UI 线程上运行,您会完全阻止它,因此setOnFinished永远不会有机会运行。您应该sort在单独的线程上运行:

    new Thread() {
        public void run() {
            new BubbleSort().sort(array, compareFunction, model, controller);
        }
    }.start();
    

如果您从此线程更新 UI,请确保将 UI 调用包装到Platform.runLater中。

于 2013-04-22T00:05:53.837 回答
0

我认为您swaping = true在方法中进行了更新,但在执行 while 循环之前setSwaping再次设置了排序方法。swaping= false所以我认为你的 while 循环永远不会执行,因为交换是错误的。所以你假设价值没有被更新。

sort从您的方法中删除此行:

swaping = false;


while (swaping);

删除;并将您的代码放入 while 块中。

于 2013-04-21T13:54:22.423 回答