2010-10-15 109 views
2
some Function() 
{ 
    for(xxxxxx){ 
     //a infinite loop or just a long code loading an running stuff from a list 
    } 
} 

ActionListener Panic(yyyyyyyy) 
{ 
    Stops the infinite loop by list.clear() or insert some thing into the list and break the loop 
} 

我試圖做一個緊急按鈕停止我的代碼,當運行Java的一些事情的問題是所有ActionListener會進行排隊,火災後我大循環完成它的東西。這可能是一個愚蠢的問題,但我似乎無法弄清楚。只有我能想到的解決方案是將其設置爲一個線程(有點難,不確定它是否可行)或給出彈出消息詢問用戶是否希望每個週期都繼續(太多提示)。只需要一個Red按鈕,它可以打破循環並破壞程序,就像linux中的Ctrl Z和eclipse中的紅色停止按鈕,或者取消按鈕來停止文件傳輸。是停止Java程序的Java緊急按鈕中間過程

感謝您尋找= d 地段和感謝

的很多哦順便說一句,如果解決方案是線程,請把它放在我前面的例子。我幾乎不知道如何線程=(

回答

2

如果你想停止一個無限的(或非常長)循環,循環必須定期確保它是否沒有中斷。

public class AlmostInfinite extends Thread { 
    public void run() { 
     while (!Thread.interrupted()) { 
      /* Do some work, not too long */ 
     } 
     cleanUp(); 
    } 

    private cleanUp() { 
     /* close network connections, files and other resources */ 
    } 
} 

ActionListener panic(AlmostInfinite t) 
{ 
    t.interrupt(); 
} 
+0

真棒!很好的例子,簡單易懂=) Ty – JavaLu 2010-10-19 07:44:38

0

最終的Java緊急按鈕實現由呼叫寫入System.exit()

這將JVM進程這意味着你需要格外確定你想以這種方式退出,因爲沒有任何東西會被清理乾淨,任何未完成的工作都將沒有完成(想想數據庫連接,交易,內存高速緩存等)

+1

請注意,人們可以在此System.exit中添加[shutdown hooks threads] [1]。 [1]:http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread) – Riduidel 2010-10-15 08:59:00

+0

很酷,感謝您的信息 – JavaLu 2010-10-19 07:44:58