线程之间怎么传参?

在日常一般的开发模式中,都是同步开发,调用方法时,通过方法的参数将数据传入,并通过方法的返回值返回结果。但是多线程属于异步开发,理论上,它的运行和结束是不可预料的。当然,java已经可以解决这个问题,比如https://www.cnblogs.com/ivy-xu/p/12375276.htmlhttps://www.cnblogs.com/ivy-xu/p/12362432.htmlhttps://www.cnblogs.com/ivy-xu/p/12361083.htmlhttps://www.cnblogs.com/ivy-xu/p/12375393.html,不过用这些解决参数传递,开销天大。我们下面介绍参数传递的几种方法。

线程参数传递方法:

  1. 构造方法
  2. set方法
  3. 回调函数

对于刚学的同学,前面2个比较简单了,我们现在来说第三种,其实也比较简单,可能名字比较不熟。现在举例说明:

 1     class Data {
 2         public int value = 0;
 3     }
 4 
 5     class Work {
 6         public void process(Data data, Integer numbers) {
 7             for (int n : numbers) {
 8                 data.value += n;
 9             }
10         }
11     }
12 
13     public class MyThread3 extends Thread {
14         private Work work;
15 
16         public MyThread3(Work work) {
17             this.work = work;
18         }
19 
20         public void run() {
21             java.util.Random random = new java.util.Random();
22             Data data = new Data();
23             int n1 = random.nextInt(1000);
24             int n2 = random.nextInt(2000);
25             int n3 = random.nextInt(3000);
26             work.process(data, n1, n2, n3);   // 使用回调函数
27             System.out.println(String.valueOf(n1) + "+" + String.valueOf(n2) + "+"
28                     + String.valueOf(n3) + "=" + data.value);
29         }
30 
31         public static void main(String[] args) {
32             Thread thread = new MyThread3(new Work());
33             thread.start();
34         }
35     }

process()称为回调函数。

原文地址:https://www.cnblogs.com/ivy-xu/p/12504086.html