按下 JButton 后,我的程序的 UI 卡住了一段时间。我发现造成这种情况的原因是信号量堵塞了 Swing 线程。这是包含对信号量的 acquire()
调用的方法:
private void fetch(int numThreads) {
//some code here
sem = new Semaphore(numThreads);
for (int i = 0; i < model.getRowCount(); i++){
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//some code here
}
这是唯一调用 fetch()
concFetchButt.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
switchButtonStates(false);
}
});
fetch(Integer.parseInt(threadsNumField.getText()));
}
据我了解,这段代码最终在 Swing 线程上运行 fetch()
,不过,据说它与 Swing 无关。
我想,我的问题是这样的:如何在程序的主线程而不是 Swing 线程上运行从 Swing 的“ActionPerformed()”调用的方法?
最佳答案
无需专门在“主”线程上运行它。只需在除 Swing UI 线程之外的任何其他线程上运行它即可。
最简单的解决方案:
- 向您的类添加 ExecutorService
- 将该代码
fetch(Integer.parseInt(threadsNumField.getText()));
放入 Runnable 对象 - 将该 Runnable 提交给 ExecutorService
大致如下:
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
fetch(Integer.parseInt(threadsNumField.getText()));
}
});
关于java - 从 ActionPerformed 调用方法并在主线程上运行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44007375/