Java - volatile变量未更新 [英] Java - volatile variable is not updating

查看:150
本文介绍了Java - volatile变量未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaFx中的交互式排序应用程序:

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


  • 数字用矩形表示

  • 每次交换两个数字时,交换矩形(使用时间轴 - 动画)

这是排序算法之一:

 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;
}

}

这是swapRectangles方法的原型:

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);
        }
    });

问题是交换变量永远不会更新(从不调用setSwaping方法)。

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

你知道为什么吗?

推荐答案


  1. 运行 while(swaping); 给处理器带来了巨大的压力,你正在全力以赴并将其交给无所事事循环。要解决这个问题,要么在内部添加sleep: while(swaping)Thread.sleep(100); 或使用更方便的同步机制,如信号量

  1. Running while(swaping); puts a hard pressure on processor, you are taking all it's power and give it to "do-nothing" loop. To solve that either add sleep inside: while(swaping) Thread.sleep(100); or use more convenient synchronization mechanism like Semaphore

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

Also if you run sort on UI thread you block it entirely, thus setOnFinished will never get a chance to be run. You should run sort on a separate thread:

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


如果你从这个帖子更新UI,请make确保你将UI调用包装成 Platform.runLater

If you update UI from this thread, make sure you wrap UI calls into Platform.runLater.

这篇关于Java - volatile变量未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆