Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report