Java Runnable thread parameter transmission so that run can access parameters

  • 2021-11-13 01:42:31
  • OfStack

Directory Java Runnable thread parameter transfer, let run access parameter preface solution Runnable implement parameter transfer has the following methods

The Java Runnable thread passes parameters, allowing run to access parameters

Preface

Do Android development, may often use Runnable thread, sometimes may need to pass parameters in, and then take out parameters in run function for use.

Solution

Customize one interface, inherit Runnable, and add one parameter transfer method


public interface MyRunnable extends Runnable {
   public MyRunnable setParam(String... param);
}

Implement this custom interface


MyRunnable sendMessage = new MyRunnable() {
    String message;
    @Override
    public MyRunnable setParam(String... param) {
        message = param[0];
        return this;
    }
 
    @Override
    public void run() {
        sendMessage(message);
    }
};

Runnable Realizes Parameter Transfer

Everyone knows that Runnable () can't pass parameters, but sometimes, when we submit tasks, we need to pass parameters, so in order to solve this problem,

There are the following methods

This is a setting interface for parameter passing, and there is a method for setting parameters in it


public interface MyRunnable extends Runnable {
    public MyRunnable setParam(String param);
}

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable() {
        //  Create a new interface, and then define the write instance variable; 
            String string ;
            @Override
            public void run() {
                //  Realize the parameter transfer of thread pool 
                System.out.println(string);
            }
            @Override
            public MyRunnable setParam(String param) {
                string = param;
                return this;
            }
        };
        new Thread(myRunnable.setParam("aaa")).start();
    }

In use, we can implement run () and setParam () methods when creating a new MyRunnable, and set the parameters to String


Related articles: