Home Java javaTutorial Detailed introduction to three methods of passing parameters to multiple threads in java

Detailed introduction to three methods of passing parameters to multiple threads in java

Jan 22, 2017 am 10:55 AM

In the traditional synchronous development model, when we call a function, the data is passed in through the parameters of the function, and the final calculation result is returned through the return value of the function. However, in the multi-threaded asynchronous development mode, the transmission and return of data are very different from the synchronous development mode. Since the running and ending of threads are unpredictable, when transferring and returning data, data cannot be returned through function parameters and return statements like functions. This article introduces several methods for passing data to threads for the above reasons. In the next article, we will introduce methods of returning data from threads.

If you want to take it first, you must give it first. Generally, when using threads, some initialization data is required, and then the thread uses these data to process and return the results. The first thing to do in this process is to pass data to the thread.

1. Pass data through the constructor
When creating a thread, you must create an instance of the Thread class or its subclass. Therefore, it is not difficult for us to think of passing data into the thread through the constructor method of the thread class before calling the start method. And save the incoming data using class variables for use by the thread (actually used in the run method). The following code demonstrates how to pass data through the constructor method:

package mythread; 
public class MyThread1 extends Thread 
{ 
private String name; 
public MyThread1(String name) 
{ 
this.name = name; 
} 
public void run() 
{ 
System.out.println("hello " + name); 
} 
public static void main(String[] args) 
{ 
Thread thread = new MyThread1("world"); 
thread.start(); 
} 
}
Copy after login

Since this method passes data while creating the thread object, the data is already in place before the thread runs, so This will not cause data to be transferred in after the thread is running. If you want to pass more complex data, you can use data structures such as collections and classes. Although it is safer to use the constructor method to transfer data, it will cause a lot of inconvenience if there is a lot of data to be transferred. Since Java does not have default parameters, if you want to achieve effects similar to default parameters, you have to use overloading. This not only makes the constructor itself too complex, but also greatly increases the number of constructors. Therefore, to avoid this situation, pass data through class methods or class variables.

2. Passing data through variables and methods
There are generally two opportunities to pass data into an object. The first opportunity is to pass the data in through the construction method when creating the object. The other opportunity is Define a series of public methods or variables (also called fields) in the class. Then after creating the object, assign values ​​one by one through object instances. The following code is a modification of the MyThread1 class, using a setName method to set the name variable:

package mythread; 
public class MyThread2 implements Runnable 
{ 
private String name; 
public void setName(String name) 
{ 
this.name = name; 
} 
public void run() 
{ 
System.out.println("hello " + name); 
} 
public static void main(String[] args) 
{ 
MyThread2 myThread = new MyThread2(); 
myThread.setName("world"); 
Thread thread = new Thread(myThread); 
thread.start(); 
} 
}
Copy after login

3. Passing data through the callback function
The two methods of passing data to the thread discussed above are most commonly used. But both methods actively pass data into the thread class in the main method. For threads, this data is passively received. However, in some applications it is necessary to obtain data dynamically while the thread is running. For example, three random numbers are generated in the run method of the following code, and then the sum of these three random numbers is calculated through the process method of the Work class, and Return the result through the value of the Data class. As can be seen from this example, three random numbers must be obtained before returning value. In other words, this value cannot be passed into the thread class in advance.

package mythread; 
class Data 
{ 
public int value = 0; 
} 
class Work 
{ 
public void process(Data data, Integer numbers) 
{ 
for (int n : numbers) 
{ 
data.value += n; 
} 
} 
} 
public class MyThread3 extends Thread 
{ 
private Work work; 
public MyThread3(Work work) 
{ 
this.work = work; 
} 
public void run() 
{ 
java.util.Random random = new java.util.Random(); 
Data data = new Data(); 
int n1 = random.nextInt(1000); 
int n2 = random.nextInt(2000); 
int n3 = random.nextInt(3000); 
work.process(data, n1, n2, n3); // 使用回调函数 
System.out.println(String.valueOf(n1) + "+" + String.valueOf(n2) + "+" 
+ String.valueOf(n3) + "=" + data.value); 
} 
public static void main(String[] args) 
{ 
Thread thread = new MyThread3(new Work()); 
thread.start(); 
} 
}
Copy after login

The process method in the above code is called a callback function. In essence, callback functions are event functions. In Windows API, callback functions are often used to interact with data between the program calling the API. Therefore, the process of calling the callback function is the original process of triggering the event. In this example, calling the process method to obtain data is equivalent to triggering an event in the run method.

For more detailed introduction to the three methods of Java passing parameters to multi-threads, please pay attention to the PHP Chinese website for related articles!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development? Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? In back-end development, how to distinguish the responsibilities of the service layer and the dao layer? Apr 19, 2025 pm 01:51 PM

Discussing the hierarchical architecture in back-end development. In back-end development, hierarchical architecture is a common design pattern, usually including controller, service and dao three layers...

How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? How to restrict access to specific interfaces of nested H5 pages through OAuth2.0's scope mechanism? Apr 19, 2025 pm 02:30 PM

How to use OAuth2.0's access_token to achieve control of interface access permissions? In the application of OAuth2.0, how to ensure that the...

See all articles