Java 从ActionPerformed调用方法并在主线程上运行
我的程序的UI在按下JButton后冻结了一段时间。我发现造成这种情况的一个原因是信号灯阻塞了Swing线程。这是包含对信号量的Java 从ActionPerformed调用方法并在主线程上运行,java,multithreading,swing,semaphore,Java,Multithreading,Swing,Semaphore,我的程序的UI在按下JButton后冻结了一段时间。我发现造成这种情况的一个原因是信号灯阻塞了Swing线程。这是包含对信号量的acquire()调用的方法: private void fetch(int numThreads) { //some code here sem = new Semaphore(numThreads); for (int i = 0; i < model.getRowCount(); i++){ try {
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
}
据我所知,这段代码最终在Swing线程上运行fetch()
,不过,据推测它与Swing无关
我想,我的问题是:如何在程序的主线程上而不是在Swing线程上运行从Swing的“ActionPerformed()”调用的方法?无需在“主”线程上专门运行该方法。只需在Swing UI线程之外的任何其他线程上运行它 最简单的解决方案是:
- 将ExecutorService添加到类中
- 将该代码放入fetch(Integer.parseInt(threadsNumField.getText())将>编码到可运行对象中
- 将该Runnable提交给Executor服务
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
fetch(Integer.parseInt(threadsNumField.getText()));
}
});
不需要在“主”线程上专门运行它。只需在Swing UI线程之外的任何其他线程上运行它 最简单的解决方案是:
- 将ExecutorService添加到类中
- 将该代码放入fetch(Integer.parseInt(threadsNumField.getText())将>编码到可运行对象中
- 将该Runnable提交给Executor服务
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
public void run() {
fetch(Integer.parseInt(threadsNumField.getText()));
}
});
main(string[])
方法使用的线程可能在激活操作侦听器时已完成。使用另一个线程,一个方便的与GUI交互的线程附带了一个SwingWorker
。感谢您的及时接受。当激活操作侦听器时,main(string[])
方法使用的线程可能已经完成。使用另一个线程,一个方便的与GUI交互的线程随SwingWorker
提供。感谢您及时接受。