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

Asked

Viewed 126 times

2

I have a method and within it a thread, I needed to "startar" it from another class and then check when Thread ran out. Is it possible to do this? my code:

Thread th;

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

Thank you in advance.

1 answer

3


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

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 of how this can be implemented depending on the need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.