我想找到一種方法來終止當前循環無限的線程。 根據我的經驗,我嘗試創建第二個線程,該線程會中斷循環無限的第一個線程,但當然是由於無限循環...第一個線程永遠無法達到睡眠功能。所以,現在我回到這個使用另一個線程終止一個線程(循環)
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();
}
}
}
看起來這可能是一些愚弄的人......一個例子是:http://stackoverflow.com/questions/4472611/java-kill- or-terminate-a-thread - '使用另一個線程'部分是隱式的。 –