我一直有问题,让我的线程正常工作100%,因为它目前正在返回我的图已经排序,即使当我仍然排序时更新排序算法中的线程。也许有一段我可能会错过的代码,因为我觉得我现在已经拥有它了。在适当的时候更新线程
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if (src == button1){
int[] array2=array;
for (int i = 1; i < array2.length; i++) {
int thingToInsert = array2[i];
int j = i - 1;
while (j >= 0 && thingToInsert<array2[j]) {
array2[j+1] = array2[j];
j--;
}
array2[j+1] = thingToInsert;
(new UpdateTextFieldThread()).execute();
}
}
}
}
private class UpdateTextFieldThread extends SwingWorker<Void, Integer>
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
ExecutorService service = Executors.newSingleThreadExecuto();
try {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(THREAD_DELAY);
display.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
return null;
}
这是我做过什么来实现我想要的东西。
private class UpdateTextFieldThread extends SwingWorker<Void, Integer[]>
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
if(base==1){
array2=array;
try {
Integer[] array3=array;
for (int i = 1; i < array3.length; i++) {
Thread.sleep(THREAD_DELAY);
int thingToInsert = array3[i];
int j = i - 1;
while (j >= 0 && thingToInsert<array3[j]) {
array3[j+1] = array3[j];
j--;
}
array3[j+1] = thingToInsert;
publish(array3);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
protected void process(java.util.List<Integer[]> list)
{
array2=list.get(list.size()-1);
display.repaint();
}
}
只是为了澄清:您希望您的程序对数组进行排序,并使每个周期至少需要一秒钟+重绘中间结果? (所以做出像整齐排序的可视化) – Ordous 2014-12-02 19:39:53
其实我想出了如何做我想做的事。我想对我的数组进行排序,并且在排序时,图表每秒都会不断更新,以显示阵列发生了什么。我编辑了上面的代码来显示。 – JCole 2014-12-05 03:41:50