簡體   English   中英

For和While Loop

[英]For and While Loop

我有一個同時運行的程序,我有這個問題,我想停止線程,但一旦我點擊輸入,for循環/ while循環不會被取消

如果我參加了for循環出的while循環,程序實際響應輸入並關閉。

class MyNumber extends Thread {

    private volatile boolean processing = true;

    public void run() {
        while (processing) {
            // Once I take this for loop out(put // beside it like right now), the enter key to stop the program then does work.
            //for(int i = 1; i<27; i++){
             System.out.println("Letter " + "i");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // }
        }
    }

    public void permSleep() {
        processing = false;
    }
}

public class LetterNumber {
    public static void main(String[] args) {
        MyNumber num1 = new MyNumber();
        num1.start();

        System.out.println("Hit enter to stop the Numbers!");
        Scanner shutter1 = new Scanner(System.in);
        shutter1.nextLine();

        num1.permSleep();
    }
}

為什么for循環導致程序關閉?

我不清楚你在問什么。 但是,如果您希望whilefor循環在processing設置為true立即終止,那就不會發生這種情況。 while將執行正文中的語句(即for循環), 然后它將測試條件( processing == true ),如果它是真的,它再次執行語句, 然后再次測試條件。 它在for循環執行時不會測試它。 設置processing變量時,它不會“注意到”。 因此,當processing設置為truefor循環將繼續運行直到完成,這可能是另外26秒。

要解決這個問題,請添加

if (!processing)
    break;

for循環中。 現在,每次通過for循環都會測試processing標志。 (如果是我,我會在while循環中放置一個“標簽”並使用它來break兩個循環。)另一種解決方法:

for(int i = 1; i<27 && processing; i++){

這意味着只要processingtruefor循環就會繼續。

注意:sleep(1000)正在進行時,這些解決方案仍然不會測試processing 因此程序在終止之前仍然可以暫停1秒鍾。 如果你真的想要一個終止sleep的解決方案,你將使用interrupt或其他一些並發功能。

它應該工作。 你的for循環大約需要27秒才能完成。 for循環結束后,它應該出來了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM