Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert several Java methods to run as non-blocking threads?

Is it possible to convert a number of methods (defined in an interface and implemented in a class) to run as non-blocking threads?

Certainly, i can wrap each single method in the run() method of a thread class. But perhaps there exists a more sophisticated way to warp several different methods in one step, i.e. by a single thread class wrapper?

According to the example of 'Adamski' below, i don't want to create a new Runnable class for every method of the interface, i.e. i would like to avoid the following:

public interface MyBusinessClass 
{
    void a();
    void b();
}


public class MyRunnable_a  implements Runnable 
{
    private final MyBusinessClass bizClass;
    public MyRunnable_a(MyBusinessClass bizClass) { this.bizClass = bizClass; }

    public void run() { bizClass.a(); }
}


public class MyRunnable_b  implements Runnable 
{
    private final MyBusinessClass bizClass;
    public MyRunnable_b(MyBusinessClass bizClass) { this.bizClass = bizClass; }

    public void run() { bizClass.b(); }
}
like image 757
rmv Avatar asked May 30 '26 11:05

rmv


1 Answers

Based on your question and comment above, you would like the invocation of a method to result in the asynchronous performance of a task. The best way to do this is via instances of Runnable and an ExecutorService.

public class MyBusinessClass {
  ExecutorService myExecutor = Executors.newCachedThreadPool(); //or whatever

  void a(){
    myExecutor.execute(new Runnable() {
        public void run() {
          doA();
        }
    });
  }    

  void b(){
    myExecutor.execute(new Runnable() {
        public void run() {
          doB();
        }
    });
  }    
}

Think of it this way, in order to run asynchronously, you need to send some kind of message to another Thread to indicate it should do work. The Executor framework in the java.util.concurrent package is the standardized way of forming those messages. They are formed in such a way that the "run" method on the Runnable instance indicates what actions should be taken.

like image 91
Tim Bender Avatar answered Jun 01 '26 01:06

Tim Bender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!