gpt4 book ai didi

java - SwingWorker 创建多线程

转载 作者:行者123 更新时间:2023-11-30 11:15:34 24 4
gpt4 key购买 nike

不知道我是否正确使用了SwingWorker。在我的需求中,我需要每秒刷新一次,所以我需要一个需要每秒执行一次的SwingWorker。

我的部分代码在下面说明了我过去是如何循环我的 SwingWorker 的。

// Parent class

/**
* Initialize background services.
*/
private void initServices() {
this.dtModel = (DefaultTableModel) tblHistory.getModel(); // Default data model of the jTable
this.updateTimer = new Timer(1000, new ActionListener() { // I don't know if this is right, I use Timer to loop the Swingworker
@Override
public void actionPerformed(ActionEvent e) {
new CallHistoryWatcherService(CallHistory.this, updateTimer, dtModel).execute();
}
});
updateTimer.setRepeats(false);
updateTimer.start();
}

// Watcher class

/**
* Watch the CallInformations if any update has been made.
* This will check every seconds.
* @param history
* @param updateTimer
* @param dtModel
*/
public CallHistoryWatcherService(CallHistory history, javax.swing.Timer updateTimer, DefaultTableModel dtModel) {
// Initialize values
}

@Override
protected Collection<Vector> doInBackground() throws Exception {
Collection<Vector> chunks = new ArrayList<>();
for (CallInformations info : CallInformations.getCallInformations(OrderBy.Ascending)) {
Vector v = new Vector();
// Get from data from Database then place it to Vector
chunks.add(v);
}
return chunks;
}

@Override
protected void done() {
try {
history.updateTableData(get()); // From parent class, manually update the data based on new Collection of data
System.out.println("Call History refreshed...");
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
COLUMN_NAMES.clear();
updateTimer.restart(); // Again, I don't know if this is right, restart the timer to execute the SwingWorker
}

最佳答案

SwingWorker 的 Javadoc 中所述:

There are three threads involved in the life cycle of a SwingWorker:

  • Current thread
  • Worker thread
  • Event Dispatch Thread

后台作业在单个工作线程上完成。但是 SwingWorker 的内部实现通过 ExecutorService 使用共享线程池来运行多个 SwingWorker 的后台作业。引用自 SwingWorker.execute() 的 Javadoc:

Schedules this SwingWorker for execution on a worker thread. There are a number of worker threads available.

所以您看到的是完全正常的,因为这些是 SwingWorker 内部使用的线程池的线程。

编辑:

在您的情况下,我不会使用 SwingWorker。我将只使用一个单独的线程(而不是 EDT)来完成工作,一旦完成,我将更新 UI,但在 EDT 中调用 SwingUtilities.invokeLater()。我会使用可重复的 Timer 定期执行这项工作。

关于java - SwingWorker 创建多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25360926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com