【问题标题】:For loop & Thread.sleepFor 循环 & Thread.sleep
【发布时间】:2012-11-19 16:43:23
【问题描述】:

我想对用户插入的数组进行排序。这部分已经ok了 我遇到的问题是,当您单击排序按钮时,它会给出某种排序 在一个 jtextarea 中一步一步的,每行之间有一些小的时间间隔。

我的问题出在哪里,我正在尝试将 Thread.sleep 放入我的 for 循环中, 让它打印一行然后暂停一点,但它没有在正确的时刻暂停 但在开始排序并一次性打印之前。

public void bubbleSort(int[] arr) {
    int[] array_to_sort = arr;
    int[] initial_array = arr;
    int count = 1;
    String result = "";
    String result2 = "";
    for (int l = 0; l < initial_array.length; l++)
        result2 += arr[l] + " ";
    for (int i = array_to_sort.length; i >= 1; i--)
        for (int j = 1; j < i; j++)
            if (array_to_sort[j - 1] > array_to_sort[j]) {
                int aux = array_to_sort[j];
                array_to_sort[j] = array_to_sort[j - 1];
                array_to_sort[j - 1] = aux;
                for (int l = 0; l < array_to_sort.length; l++)
                    result += array_to_sort[l] + " ";
                Interface.jTextArea1.append(result + "\n"); // I'd like to pause after printing this line
                result = "";
                count++;
            }
}

有人能告诉我如何以正确的方式暂停吗?

【问题讨论】:

  • 不能从 UI 线程(例如事件回调)使用 Thread.sleep 并期望 UI 更新:它将“挂起”直到操作完成。并且不能直接从非 UI 线程更新 UI(但有一些方法可以在 EDT 上对更新进行排队)。
  • @pst 调用 SwingUtilities.invokeLater() 是一个很好的解决方案,然后呢? (我在问,因为我不确定)
  • @pst 说了什么。那将是预期的行为。看看你是否可以在睡眠前立即触发重绘。
  • @LaurentBERNABE 如果排序在 工作线程 上运行,那么这是一种对 UI 控件更新进行排队的适当机制。
  • 你不应该睡在 EDT 上。这会导致 GUI 冻结。检查这个post

标签: java arrays sorting for-loop sleep


【解决方案1】:

Interface.jTextArea1.append(result + "\n"); // I'd like to pause after printing this line

执行以下操作for(int i = 0; i &lt; Short.MAX_VALUE;i++);
我的意思是做一个空循环来模拟你的延迟。虽然正确的解决方案是重组您的代码,以便在 EDT 中间隔发送要打印的文本。

【讨论】:

    猜你喜欢
    • 2015-01-12
    • 2020-10-24
    • 2012-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多