是否有任何有效的方法来保持一个线程,其中包含ActionListener的run方法,直到发生点击事件为止?

时间:2016-04-20 13:04:44

标签: java multithreading actionlistener

      boolean flag = true;
      public void run(){
      // some code
         loginButton.addActionListener(new ActionListener() { 
         public void actionPerformed(ActionEvent e) {
             flag = false; 
             // Some code
         }
      }); 

      while(flag){}
      }

我正在使用while循环直到调用actionListener,我认为这可能是愚蠢的。如果能以更有效的方式完成,请告诉我。

1 个答案:

答案 0 :(得分:0)

您不需要监听器本身的线程,Java UI线程会为您调用监听器。

但是,如果您希望对非阻塞事件的响应,请执行以下操作:

// no need for a second thread here
loginButton.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) {
         // If you dont want to block the UI Thread make a new Thread here
         new Thread(YOUR_RUNNABLE).start();
     }
}

Related Question