¿Por qué se terminan mis hilos?

I'm trying to repeat calls to methods through 3 differents threads. But after I start my threads, during the next iteration of my loop, they are all terminated so nothing is executed... The code is as follows :

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
    }
}

And for some reason, when I test the state of my different threads, they appear as runnable and then a the 2nd iteration, they are all terminated... What am I doing wrong? I actually have no error, but the threads are terminated and so my loop keeps looping and telling me the threads are terminated....

preguntado el 08 de enero de 11 a las 23:01

1 Respuestas

I do not know what is inside the run() methods, but if the comments are correct, if you just create something and return, the threads are probably terminated quickly: returning from run() makes the thread exit. Usually you would have some kind of while loop in there testing for a termination condition if you want your threads to be alive for a longer time.

Respondido el 09 de enero de 11 a las 02:01

Indeed, this does help a lot. Now I have other issues but not with threads anymore. Thanks for the quick answer. - Sephy

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.