Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Queue of methods in Java

My goal is to have a Queue of method calls contained in a class that extends Thread whose run method pops a method call off of the queue once every 15 seconds. This could be done in a shady way using Strings, ints, or chars in a mammoth switch case, but I was wondering if anyone else has a far more elegant solution to this issue.

Something that would look like this?

public class Potato extends Thread{
    Queue<Methods> methodsQueue = new LinkedList<Methods>();

    public Potato(){}
    run(){
        methodsQueue.poll();//This would execute a method
    }

    //Methods of this class...
}
like image 905
PerryJ Avatar asked Jul 01 '26 12:07

PerryJ


1 Answers

You can use an interface to wrap the methods you want to call:

public interface MethodWrapper {
  void execute();
}

public class Potato extends Thread{
  Queue<MethodWrapper> methodsQueue = new LinkedList<>();
  public Potato(){}
  run(){
   methodsQueue.poll().execute();
  }

//Methods of this class...
}
like image 110
Nir Levy Avatar answered Jul 03 '26 01:07

Nir Levy



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!