gpt4 book ai didi

java - 如何使用两个Swing Worker实例?

转载 作者:行者123 更新时间:2023-12-01 22:36:17 24 4
gpt4 key购买 nike

我已经创建了 SwingWorker 实例并将其安排在工作 thread(tAccess = new TimeAccess()).execute()) 这个实例中以访问时间。但我需要另一个 Swing Worker 实例来持续访问数据库。这个怎么做?

// when execute both instances ,sometimes GUI become unresponsive. 

tAccess = new TimeAccess()).execute();
dAccess = new DataAccess()).execute();

代码:

public class DataAccess extends SwingWorker<Void, ArrayList<TimeTable>> {

@Override
protected Void doInBackground() throws SQLException, ClassNotFoundException {
int timeRun = 0;
ArrayList<TimeTable> timeList = null;
while (timeRun == 0) {
timeList = TimeTableController.viewTimeTable();
publish(timeList);

}
return null;
}

@Override
protected void process(List<ArrayList<TimeTable>> dataList) {
ArrayList<TimeTable> timeArray = dataList.get(dataList.size() - 1);
DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
int x = 0;
for (TimeTable time : timeArray) {
dtm.setValueAt(time.getCity() + " " + time.getTime(), x, 0);
dtm.setValueAt(time.getCity() + " " + time.getTime(), x, 1);
x = x + 1;
// System.out.println(x);
System.out.println(javax.swing.SwingUtilities.isEventDispatchThread() + "database thread chkr");

}

}

}


private class TimeAccess extends SwingWorker<Void, String> {

@Override
protected Void doInBackground() {
int timeRun = 0;
while (timeRun == 0) {
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(sdf.format(cal.getTime()));
String timeNow = sdf.format(cal.getTime());

publish(timeNow);

}
return null;
}

@Override
protected void process(List<String> timeList) {
String time = timeList.get(timeList.size() - 1);
clockLabel.setText(time);
System.out.println(javax.swing.SwingUtilities.isEventDispatchThread());
}

}

最佳答案

问题似乎是这里有一个无限循环:

while (timeRun == 0) {

调用一些方法:

TimeTableController.viewTimeTable();

我假设这个方法不会阻塞,或者任何合理的事情。所以:

  1. 工作线程循环并每秒调用publish很多次;那么
  2. 发布会获取所有数据,并且每次都会更新整个显示表格。

这显然占用了 EDT 的所有时间 - 试图跟上您要求的更新。

所以,使用 SwingWorker 做得很好。多思考一下你的逻辑。

关于java - 如何使用两个Swing Worker实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828204/

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