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

Asked

Viewed 992 times

4

I have an application where each process is called by a single method and this process needs to run in a thread.

The code of the threads is identical in all, changing only the content of the method run().

I wouldn’t want to keep copying and pasting dozens of times the same code.

It is possible to do something similar to 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;
    }
}
  • 1

    The kind of behavior you’re trying to get (updating a progressibar while running a background task) suggests that you should try using AsyncTask.

  • @Piovezan , was just an example. But thanks for the tip! Another learning!

  • Well, in Delphi (which is my area), you can send an anonymous method. I believe that in Java, there is something similar

2 answers

4


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

Declare a class that implements Runnable for each of the tasks it wishes 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 call the "Process Methodshow"

Change the method metodoComThread() thus:

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 particular task, call the method like this:

metodoComThread(new Tarefa1());

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

metodoComThread(new Runnable() {
        public void run()
        {
            // código a executar
        }
    });
  • Thank you so much ramaral! Once I test I give you a feedback.

2

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

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 method parameter metodoComThread is the type Runnable. The interface Runnable is a functional interface, as it has only one abstract method. The method in question of the interface Runnable is the run, that has no parameters and has return void. Time the methods metodo1 and metodo2 also have no parameters and are also void, then they are compatible with Runnable.

  • I’m implementing in Android Studio. I don’t know if it supports this version of Java. I tried running here, he suggested that I modify the JAVA version in the IDE, but it gave some strange errors. But his reply to my view is valid. I just couldn’t test.

  • 1

    @Alexql See this: https://developer.android.com/guide/platform/j8-jack.html

  • Thank you! I will try again. My application needs to run with version of at least Android 4.0. Let’s see this J8-jack works in this version.

Browser other questions tagged

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