【发布时间】:2013-04-29 03:02:31
【问题描述】:
我尝试了各种方法来启动线程并将其输出到控制台,但到目前为止没有任何效果。我有一个名为 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);
}
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
“我不确定使用 Executor 服务而不是带计时器的线程是否可以打印到 GUI?” 这实际上不是问题。 OTOH 我不会使用普通的
Thread来更新 GUI,而是使用事件调度线程。为了尽快获得更好的帮助,请发布SSCCE。就目前而言,我觉得你的问题难以理解。 -
我的主要问题是如何将线程输出到我的 GUI 上的文本字段。当我说 “我不确定使用 Executor 服务而不是带计时器的线程是否可以打印到 GUI 上?” 我的意思是输入句号而不是问号对不起。无论如何,您可以在主要问题上帮助我吗?
标签: java multithreading user-interface