我正在尝试找到一种方法来终止当前无限循环的线程。以我的经验,我尝试创建第二个线程,该线程将中断第一个无限循环的线程,但当然由于无限循环......第一个线程永远不会到达睡眠功能。所以现在我回到这个
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();
}
}
}