簡體   English   中英

帶有while語句的無限while循環

[英]Infinite while loop with break statement

我是一個初學者,正在分析以下Java代碼:

// t is a thread running
while (true) {
    try {
        t.join(); 
    } catch (InterruptedException e) { e.printStackTrace(); }
    break;
}
t=null;

我要問的是:是否需要將其放入無限循環內? 因為如我所見,循環僅運行一次,即由於該break語句。 我需要一些解釋。

不,沒有必要。 您的觀察是正確的,循環將僅執行一次。

因此,OP發布的代碼等效於以下代碼。

// t is a thread running
try {
    t.join(); 
} catch (InterruptedException e) { e.printStackTrace(); }
t=null;

OP發布的代碼:

// t is a thread running
while (true) {
    try {
        t.join(); 
    } catch (InterruptedException e) { e.printStackTrace(); }
    break;
}
t=null;

正如每個人都已經指出的那樣,代碼本身是不正確的。

但是,循環必要的

正確的代碼如下所示:

while (true) {
    try {
        t.join();
        break; 
    } catch (InterruptedException e) { e.printStackTrace(); }
}
t = null;

如果沒有循環,則可以在當前線程成功加入之前t設置為null。

t.join(); 等待線程完成。
在那之后,循環被您的“中斷”所中斷。
=>總是只循環1次=>不需要循環和中斷,只需要t.join();

無需進行while循環,因為t.join()等待線程死亡。 就像一個循環一樣,在t.join()的程序中,線程未死亡時,程序將被阻塞。

正確的代碼是:

// t is a thread running
    try {
        t.join(); 
    } catch (InterruptedException e) { e.printStackTrace(); }

    t=null;

這里有一個例子:

http://www.tutorialspoint.com/java/lang/thread_join.htm

循環是沒有必要的! 據說線程t已經啟動。 因此,“ t = null”是沒有意義的。 線程t已經啟動,它將完成其工作。 您可以使用不帶while循環的t.join()。 在這種情況下,while循環是沒有意義的。 join方法允許一個線程等待另一個線程的完成。 如果t是當前正在執行線程的Thread對象,

t.join();

導致當前線程(下例中的主線程)暫停執行,直到t的線程終止為止。運行以下代碼片段並了解繩索。

public class Main {

public static void main(String[] args) {

    Thread t=new Thread(
         new Runnable() {
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName()+"--"+i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        });

    t.start();

    try {
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    t = null;  // no sense, t is already started

    for (int i = 0; i < 100; i++) {
        System.out.println(Thread.currentThread().getName()+"--Thread--"+i);
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

暫無
暫無

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

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