There is a good answer , but it’s not quite clear how the methods are added to the queue, why the MethodWrapper interface is needed, and how this whole construct works.

from the answer

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... } 

    1 answer 1

    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?

    1. A queue is created for objects that implement the MethodWrapper interface.
    2. methodsQueue.poll() returns the first element of the queue and deletes it, that is, the output is an object that implements MethodWrapper.
    3. 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() { // Тело метода } }); 
    • Yes, I have already found that the pattern is called Command, now I am thinking why I need it if there are lambda expressions. It seems like the latter is simpler and, it seems to me, less resource intensive. - Oleg Kotenko
    • Not sure about performance, but it improves code readability. - KeterDev
    • one
      Just about readability - easier. But why this pattern appeared (write-appeared before lambda expressions) and is used in some projects (I found its use in ThirtyInchMVP) ... - Oleg Kotenko
    • Here's another question - how does the add () method take as input a lambda expression, if it doesn't apply to MethodWrapper at all? - Oleg Kotenko
    • MethodWrapper has one method, so you can use lambda, which is the same as an anonymous class, i.e. interface implementation. - KeterDev