我的问题是关于我目前正在进行的Java项目。我必须构建一个模拟,以概念/视觉方式显示各种不同排序算法的工作方式。其中包括:冒泡排序,插入排序,合并排序等。这必须允许用户逐步完成流程的每个步骤或选择他们希望在其中执行的速度。这必须通过使用线程来完成。排序算法都在一个类中,用户从结尾选择的任何一个都将在线程内运行。
e.g。 sort.bubbleSort(对象); <对象是要排序的对象数组。
我的问题是我不知道如何操纵线程的速度。对于一步一步,我将需要它在例如执行算法的每一行之后暂停。该项目还实现了MVC。该线程位于Contoller包中,排序类位于Model中。任何可以帮助我的人都会非常感激。
答案 0 :(得分:0)
我没有任何魔术类型的解决方案。我认为您必须在代码的各个地方放置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问题发表评论。您将不得不针对您尝试过的内容以及您想要完成的内容撰写另一个更具体的问题。