我一直有問題,讓我的線程正常工作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