我的问题是关于我目前正在从事的一个Java项目。我必须构建一个模拟,从概念上/视觉上展示各种不同排序算法的工作原理。这些包括:冒泡排序,插入排序,合并排序和其他一些排序。这必须允许用户逐步执行该过程的每个步骤,或者选择他们希望其执行的速度。这必须通过使用线程来完成。排序算法都在一个类中,无论用户从from端选择哪一个,都将在线程中运行。
例如sort.bubbleSort(对象);<对象是要排序的对象的数组。
我的问题是我不知道如何控制线程的速度。例如,对于step by step,我需要在执行算法的每一行后暂停。该项目还实现了MVC。线程在Contoller包中,排序类在Model中。任何人谁可以帮助我这将非常感谢。
发布于 2012-04-12 23:34:35
我没有任何神奇的子弹式解决方案。我认为您将不得不在代码中的各个位置放置Thread.sleep(...)调用。
public class BubbleSort {
private long sleepBetweenIterationsMillis;
public BubbleSort(long sleepBetweenIterationsMillis) {
this.sleepBetweenIterationsMillis = sleepBetweenIterationsMillis;
}
...
// iterate through the list bringing the highest value to the top
// wait a certain number of millis
Thread.sleep(sleepBetweenIterationsMillis);
// loop
...
}选择排序算法中的点来放置这些休眠调用取决于您认为的“迭代”是什么。与注入休眠值不同,您可以调用某个休眠管理器,该管理器可以根据用户输入动态更改休眠值或其他内容。
public interface SleepManager {
public void sleep();
}
public class BubbleSort {
private SleepManager sleepManager;
public BubbleSort(SleepManager sleepManager) {
this.sleepManager = sleepManager;
}
...
// iterate through the list bringing the highest value to the top
// call the manager which can dynamically slow or speed up the iterations
sleepManager.sleep();
// loop
...
}我不能对MVC的问题发表评论。你将不得不写另一个更具体的问题,围绕你已经尝试过的东西和你想要完成的东西。
https://stackoverflow.com/questions/10126583
复制相似问题