2011-05-13 135 views
1

我有一個swing應用程序。點擊菜單欄上的menuItem後,我試圖進行API調用,這將需要一些時間。在SwingUtilities.invokeLater()中殺死一個線程

我不希望Swing應用卡住/掛起,直到API調用給出結果,所以我使用了SwingUtilities.invokeLater來分離出一個新產生的線程來處理API調用。以下是上述

public void actionPerformed(ActionEvent e){ 
    Object src=e.getSource(); 

    if(src.equals(theJMenuItemClicked)){ 
     SwingUtilities.invokeLater(new Runnable() { 

        @Override 
        public void run() { 
         //apicall here 
        } 
       }) 
    } 

代碼只要API調用線程運行我展示一個JDialog有消息說「進展API調用」和「中止線程」按鈕。

我想通過單擊Jdialog中的「ABort Thread」按鈕來終止線程。

如果是普通線程,我們有一個Thread t = new Thread(new Runnable()),我們調用t.stop

如何獲取由SwingUtilities產生的特定線程實例,以便我可以在其上調用一個停止點?用更簡單的話來說,我怎樣才能殺死上面創建的線程?

回答

0
public class SwingUtilitiesExample implements ActionListener { 

// Declaration of Swing Components 
private JMenuItem menuItem; 
private JButton abortOperation; 

// Thread-safe indicator of the presence of the Thread 
private volatile boolean isThreadRunning = false; 

public SwingUtilitiesExample() { 
    // Initialize Swing Components 
    menuItem = new JMenuItem(); 

    // Add ActionListeners 
    menuItem.addActionListener(this); 
    abortOperation.addActionListener(this); 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
    Object source = e.getSource(); 
    if (source.equals(menuItem)) { 
     isThreadRunning = true; 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       while (isThreadRunning) { 
        // API calls here 
       } 
      } 
     }); 
    } else if (source.equals(abortOperation)) { 
     isThreadRunning = false; 
    } 
} 
} 

通過將isThreadRunning的值更改爲false,可以有效地中止線程。只要Thread定期檢查這個布爾值,這個代碼就可以正常工作。

方法Thread.stop()已棄用。 Oracle指出the method is inherently unsafe。因此,你應該避免使用它。如上面的代碼示例所示,嘗試使用線程安全布爾變量來控制線程的流向。

如果您在完成線程後正在考慮返回某種類型,則可能需要考慮SwingWorker類。