使用另一个线程终止一个线程(循环)

时间:2012-05-03 14:42:45

标签: java multithreading infinite-loop

我试图找到一种方法来终止当前循环无限的线程。 根据我的经验,我尝试创建第二个线程,它将中断第一个循环无限的线程,但当然由于无限循环...第一个线程永远不会到达睡眠函数。所以现在我回到了这个

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();
    }
}
}

4 个答案:

答案 0 :(得分:2)

拥有volatile boolean字段,例如running。设为true。您将while (true)更改为while (running)while ( System.currentTimeMillis() < stop ) {更改为while (running && ( System.currentTimeMillis() < stop) ) { 的位置。现在,从其他线程更改runningfalse。这应该可以很好地停止循环。

答案 1 :(得分:1)

你能改变吗?

 while(true){

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

现在当你中断线程时,它应该正确地突破无限循环。

答案 2 :(得分:1)

你必须在循环中进行Thread.interrupted()调用,以检查它是否被中断并正确处理它。或者改为(!Thread.interrupted())。

答案 3 :(得分: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;
    }
}