1

我尝试了各种方法来启动线程并将其输出到控制台,但到目前为止没有任何效果。我有一个名为 BankAccount 的主要方法,其中包含使用执行程序服务创建的线程。我尝试使用以下方法:

public void run() {
        // Updating of textboxes 
        jTextField22.setText(BankMain.executorService);
    }
});

但这不起作用,我正在搜索并找到有关异步和同步方法的一些信息,但对这个确切问题没有足够的解释。我不确定使用 Executor 服务而不是带有计时器的线程是否可以打印到 GUI?我还希望线程在 52 秒后停止,当我输入 52.seconds 时它不起作用。我的线程代码:

final BankAccount accountBalance = new BankAccount(0);
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    //print balance  - monthly
    executorService.scheduleAtFixedRate(new Statement(accountBalance), 0, 4, TimeUnit.SECONDS);
    //income - monthly
    executorService.scheduleAtFixedRate(new Incomming("Wage", 2000, 4000, accountBalance), 0, 4, TimeUnit.SECONDS);
    //
    executorService.scheduleAtFixedRate(new Incomming("Interest", 10, 4000, accountBalance), 0, 4, TimeUnit.SECONDS);
    //rent - monthly
    executorService.scheduleAtFixedRate(new Consumables("Oil Bill", 250, 3000, accountBalance), 0, 3, TimeUnit.SECONDS);
    //

    //food - weekly
    executorService.scheduleAtFixedRate(new Consumables("Food Bill", 60, 1000, accountBalance), 0, 1, TimeUnit.SECONDS);
    executorService.scheduleAtFixedRate(new Consumables("Electricity Bill", 50, 1000, accountBalance), 0, 1, TimeUnit.SECONDS);
    executorService.scheduleAtFixedRate(new Consumables("Entertainment Bill", 400, 1000, accountBalance), 0, 1, TimeUnit.SECONDS);
    executorService.scheduleAtFixedRate(new Consumables("Shoppping Bill", 200, 1000, accountBalance), 0, 1, TimeUnit.SECONDS);

    //shutdown after a 52 secs
    executorService.schedule(new Runnable() {
        @Override
        public void run() {
            accountBalance.getBalance();
            executorService.shutdown();
        }
    }, 10, TimeUnit.SECONDS);
}

任何帮助将非常感激。谢谢!

4

1 回答 1

0

从多个线程到 UI 的输出应该包含在Runnables 中。您当前启动Runnables 来做一些工作,但结果应该在单独Runnable的 s 中发布并添加到事件调度线程(UI 线程)中SwingUtilities.invokeLater()。我会这样做...

class Consumables implements Runnable /* or TimerTask or other implementor of Runnable */
{
  public void run()
  {
    // Do your work here
    String result = doTheWork();

    // Post results
    SwingUtilities.invokeLater(new PrintTask(result));
  }
}

private class PrintTask implements Runnable
{
  private final String mResult;

  public PrintTask(int result)
  {
    mResult = result;
  }

  public void run()
  {
    jTextField22.setText(mResult);
  }
}
于 2013-04-29T09:47:24.273 回答