gpt4 book ai didi

java - 从 ActionPerformed 调用方法并在主线程上运行它

转载 作者:太空宇宙 更新时间:2023-11-04 11:29:05 25 4
gpt4 key购买 nike

按下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com