我已经尝试了各种方法来让线程启动并输出到控制台但到目前为止还没有任何工作。我有一个名为BankAccount的main方法,它包含使用执行程序服务创建的线程。我尝试使用这个方法:
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);
}
非常感谢任何帮助。谢谢!
答案 0 :(得分:0)
从多个线程输出到UI应该包含在Runnable
内。您目前正在启动Runnable
来完成一些工作,但结果应该在单独的Runnable
中发布,并添加到带有SwingUtilities.invokeLater()
的事件调度线程(UI线程)中。我会这样做......
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);
}
}