Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement Java Runnable thread to pass parameters and let run access parameters

Shulou Source: shulou.com Published: 2022-06-03 15:50:54 10月29日 Update

How to implement Java Runnable thread parameters and let run access parameters, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need this to learn, I hope you can harvest.

Java Runnable thread parameters, let run access parameters

Customize an interface, inherit Runnable, add a parameter passing 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 implements parameter passing

We all know that Runnable() cannot pass parameters, but sometimes, when we submit tasks, we need to pass parameters, so in order to solve this problem,

There are the following ways

This is a parameter transfer setting interface, which has a method for setting parameters.

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() { //implement thread pool parameters System.out.println(string); } @Override public MyRunnable setParam(String param) { string = param; return this; } }; new Thread(myRunnable.setParam("aaa")).start(); }

When using, we can implement run() and setParam() methods when creating MyRunnable, and set parameters to String

Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.

Tags: Parameters interfaces methods threads time help Chinese clear tasks content variables this articles novices more sometimes knowledge industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MySQL macOS Redmi NVidia