In the code, everything is quite simple.
why do we need interface MethodWrapper
This interface, as the name implies, is a wrapper for the method that is added to the queue. The interface needs to be implemented (how to do this, see below, where the code is) and in the execute() method add the body of the method to be placed in the queue.
and how does this whole construct work?
- A queue is created for objects that implement the MethodWrapper interface.
methodsQueue.poll() returns the first element of the queue and deletes it, that is, the output is an object that implements MethodWrapper.- In the resulting MethodWrapper, the
execute() method is called, i.e. the method placed in the queue. The interface was needed for this method to execute the code that you need.
Here is an example of use (took your code as a basis):
public interface MethodWrapper { void execute(); } public class Potato extends Thread { Queue<MethodWrapper> methodsQueue = new LinkedList<>(); public Potato () { methodsQueue.add(() -> { // Тело метода, который нужно поставить в очередь. }); } public void run() { methodsQueue.poll().execute(); } }
I used the lambda function, but if you need an anonymous class (for Java 7), then this is the code:
methodsQueue.add(new MethodWrapper() { @Override public void execute() { // Тело метода } });