为什么我的线程被终止了?

时间:2011-01-08 23:40:01

标签: java multithreading

我正在尝试通过3个不同的线程重复调用方法。但是在我开始我的线程之后,在我的循环的下一次迭代中,它们都被终止,因此没有执行任何内容...... 代码如下:

public static void main(String[] args) {
    main = new Main();
    pollingThread.start();
}
static Thread pollingThread = new Thread() {
    @Override
    public void run() {
        while (isRunning) {
            main.poll();
                // test the state of the threads
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
};

public void poll() {
    if (clientThread == null) {
        clientThread = new Thread(new Runnable() {

            @Override
            public void run() {
                //create some objects
            }
        });
        clientThread.start();
    }       
    else if (clientThread.isAlive()) {
        // do some treatment
    }

    if (gestionnaireThread == null) {
        gestionnaireThread = new Thread(new Runnable() {
            @Override
            public void run() {
                //create some objects
            };
        });
        gestionnaireThread.start();
    }

    else if (gestionnaireThread.isAlive()) {
        // do some treatment
    }

    if (marchandThread == null) {
        marchandThread = new Thread(new Runnable() {
            @Override
            public void run() {
                // create some objects
            };
        });
        marchandThread.start();
    }

    else if (marchandThread.isAlive()) {
        // do some treatment
    }
}

由于某种原因,当我测试我的不同线程的状态时,它们看起来是可运行的,然后是第二次迭代,它们都被终止了...... 我究竟做错了什么? 我实际上没有错误,但线程被终止,所以我的循环保持循环并告诉我线程被终止....

1 个答案:

答案 0 :(得分:2)

我不知道run()方法中的内容是什么,但如果注释是正确的,如果您只是创建并返回,则线程可能很快终止:从run()返回使线程退出。通常,如果您希望线程在更长的时间内处于活动状态,那么在那里测试终止条件会有某种while循环。