Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从ActionPerformed调用方法并在主线程上运行_Java_Multithreading_Swing_Semaphore - Fatal编程技术网

Java 从ActionPerformed调用方法并在主线程上运行

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 {

我的程序的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 {
        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
提供。感谢您及时接受。