ScheduledThreadPoolExecutor(實現ScheduledExecutorService)在使用ScheduleAtFixedRate方法時似乎只運行一次SwingWorker類。原來的代碼有點長,所以我做了一個新的代碼,在下面產生相同的結果。ScheduledThreadPoolExecutor只運行Swingworker一次
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ScheduledThreadPoolExecutorTest extends SwingWorker<Void, Void>{
@Override
protected Void doInBackground() {
System.out.println("Yay!");
return null;
}
@Override
protected void done() {
try {
get();
} catch(Exception e) {
e.printStackTrace();
}
System.out.println("Woohoo!");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new ScheduledThreadPoolExecutorTest(), 0, 30, TimeUnit.MILLISECONDS);
}
});
}
}
這樣產生的結果:
Yay!
Woohoo!
爲什麼的ScheduledThreadPoolExecutor運行的SwingWorker只有一次?我能做些什麼來使SwingWorker每30毫秒運行一次,如代碼中所示?
因此'doInBackground()'只被調用一次每個類而不是每個類的實例一次?另外,如果你完全需要使用SwingWorker,因爲你正在使用Swing對象,並且需要調用'repaint()'(當然這裏沒有顯示,但是在原始代碼中)? – ICanCYou
@ICanCYou:每個實例調用一次 - 您只是創建一個實例。 –
@ICanCYou:如果需要,也可以創建多個SwingWorkers,或者可以使用SwingUtilieis將Swing調用隊列到事件線程中。注意''repaint()'不需要在事件線程上調用。 –