Is there any way to start a Thread that is in a method in another class?

2

I have a method and inside it a thread, I needed to "start" it from another class and then check when the thread is gone. Is it possible to do that? my code:

Thread th;

public void inserir(){
    th = new Thread(){
        public void run(){
            //aqui ficam minhas inserções
        }
    };
}

Thank you in advance.

    
asked by anonymous 03.11.2015 / 19:04

1 answer

3

The correct way to resolve this is to extract the anonymous class that implements the thread so that you can reuse it.

Example:

class MinhaClasse {

    //inner class
    private Runnable insercao = new Runnable() {
        public void run() {
            //aqui ficam minhas inserções
        }
    };

    //executa e continua
    public void inserirAssincrono() {
        new Thread(insercao).start();
    }

    //executa e espera
    public void inserirSincrono() {
        Thread t = new Thread(insercao);
        t.start();
        try {
            t.join(); //espera a thread terminar antes de continuar
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}

However, there are several possibilities for how this can be implemented depending on the need.

    
04.11.2015 / 05:23