Is it possible to pass a method as a parameter to run in a thread?

4

I have an application where each process is called by a single method and this process needs to be executed on a thread. The threads code is identical in all, changing only the content of the run () method. I would not want to be copying and pasting the same code dozens of times. Is it possible to do something like the example below?

public void metodoComThread(? metodoPassadoComoParametro) //<-- Aqui passei o método!
{ 
    try {
        Thread t = new Thread(new Runnable() {
            public void run()
            {
                metodoPassadoComoParametro(); // <-- executando o método passado como parâmetro
            }
        });

        t.start();

        while (t.isAlive()) {
            try {
                //...
                // faz alguma coisa, atualiza um progressbar, etc
                //...

                Thread.sleep(100);              
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return true;
    }
    catch(Exception e) {
        return false;
    }
}
    
asked by anonymous 31.08.2016 / 08:09

2 answers

4

You just need to pass an object from a class that implements the Runnable interface.

Declare a class that implements Runnable for each of the tasks you want to perform:

public class Tarefa1 implements Runnable{

    @Override
    public void run()
    {
        //código para executar a tarefa1
    }
}

public class Tarefa2 implements Runnable{

    @Override
    public void run()
    {
        //código para executar a tarefa2
    }
}

These classes replace what you called the "PastPosition method"

Change method metodoComThread() like this:

public void metodoComThread(Runnable tarefa) //Aqui passei a tarefa a executar
{ 
    try {
        Thread t = new Thread(tarefa);

        t.start();

        while (t.isAlive()) {
            try {
                //...
                // faz alguma coisa, atualiza um progressbar, etc
                //...

                Thread.sleep(100);              
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return true;
    }
    catch(Exception e) {
        return false;
    }
}

When you want to perform a certain task, call the method like this:

metodoComThread(new Tarefa1());

If you do not want to have the classes declared at startup, you can create them by calling the method:

metodoComThread(new Runnable() {
        public void run()
        {
            // código a executar
        }
    });
    
31.08.2016 / 12:16
2

You can use references to methods that exist in Java 8 onwards.

For example:

public class MinhaClasse {
    public void metodo1() {
        System.out.println("Metodo 1");
    }

    public void metodo2() {
        System.out.println("Metodo 2");
    }

    public boolean metodoComThread(Runnable metodoPassadoComoParametro) { 
        try {
            Thread t = new Thread(metodoPassadoComoParametro);
            t.start();

            while (t.isAlive()) {
                try {
                    //...
                    // faz alguma coisa, atualiza um progressbar, etc
                    //...

                    Thread.sleep(100);              
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        MinhaClasse mc = new MinhaClasse();
        mc.metodoComThread(mc::metodo1);
        mc.metodoComThread(mc::metodo2);
    }
}

Note that the parameter of method metodoComThread is of type Runnable . The Runnable interface is a functional interface, since it has only one abstract method. The method in question of the Runnable interface is run , which has no parameters and has void return. Since metodo1 and metodo2 methods also have no parameters and are also void , then they are compatible with Runnable .

    
31.08.2016 / 15:59