如何使用两个swing worker实例?

时间:2014-11-09 12:33:04

标签: java swing concurrency

我创建了SwingWorker实例,并在此实例的worker 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());
    }

}

1 个答案:

答案 0 :(得分:3)

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

while (timeRun == 0) {

调用一些方法:

TimeTableController.viewTimeTable();

我将假设此方法不会阻止,或者任何合理的方法。所以:

  1. 工作人员循环,并且,每秒一定次数,呼叫publish;然后
  2. 发布会获取所有数据,并且每次都会更新整个显示表。
  3. 这显然占用了EDT的所有时间 - 试图跟上你要求的更新。

    所以,使用SwingWorker做得很好。更多地考虑你的逻辑。