2012-05-03 70 views
0

我想找到一種方法來終止當前循環無限的線程。 根據我的經驗,我嘗試創建第二個線程,該線程會中斷循環無限的第一個線程,但當然是由於無限循環...第一個線程永遠無法達到睡眠功能。所以,現在我回到這個使用另一個線程終止一個線程(循環)

public class Pulse{ 

private static int z = 0; 

public static void main(String[] args) throws Exception { 
    try { 
     final long stop=System.currentTimeMillis()+5L; 
      //Creating the 2 threads 
     for (int i=0; i<2; i++) { 
      final String id=""+i+": "; 
      new Thread(new Runnable() { 
       public void run() { 
        System.err.println("Started thread "+id); 
        try{ 
         while (System.currentTimeMillis() < stop) { 
            //Purposely looping infinite 
          while(true){ 
           z++; 
           System.out.println(z); 
          } 
         } 
        } catch (Exception e) { 
         System.err.println(e); 
        } 
       } 
      }).start(); 
     } 
    } catch (Exception x) { 
     x.printStackTrace(); 
    } 
} 
} 
+0

看起來這可能是一些愚弄的人......一個例子是:http://stackoverflow.com/questions/4472611/java-kill- or-terminate-a-thread - '使用另一個線程'部分是隱式的。 –

回答

2

有一個volatile boolean場,說running。做它true。如果您有while (true)更改爲while (running)while (System.currentTimeMillis() < stop) {while (running && (System.currentTimeMillis() < stop)) { 。現在,從其他某個線程將running更改爲false。這應該很好地阻止循環。

1

你能不能改

while(true){ 

while(!Thread.currentThread().isInterrupted()){ //or Thread.interrupted() 

現在,當你中斷線程應該正確地跳出無限循環的。

1

您必須在循環內執行一次Thread.interrupted()調用,以檢查它是否被中斷並正確處理。或者while(!Thread.interrupted())。

1

你必須做這樣的事情:

public class ThreadStopExample { 
    public static volatile boolean terminate = false; 

    public static void main(String[] args) { 
     new Thread(new Runnable() { 
      private int i; 

      public void run() { 
       while (!terminate) { 
        System.out.println(i++); 
       } 
       System.out.println("terminated"); 
      } 
     }).start(); 
     // spend some time in another thread 
     for (int i = 0; i < 10000; i++) { 
      System.out.println("\t" + i); 
     } 
     // then terminate the thread above 
     terminate = true; 
    } 
}