在日常一般的開發模式中,都是同步開發,調用方法時,通過方法的參數將數據傳入,並通過方法的返回值返回結果。但是多線程屬於異步開發,理論上,它的運行和結束是不可預料的。當然,java已經可以解決這個問題,比如https://www.cnblogs.com/ivy-xu/p/12375276.html,https://www.cnblogs.com/ivy-xu/p/12362432.html,https://www.cnblogs.com/ivy-xu/p/12361083.html,https://www.cnblogs.com/ivy-xu/p/12375393.html,不過用這些解決參數傳遞,開銷天大。我們下面介紹參數傳遞的幾種方法。
線程參數傳遞方法:
- 構造方法
- set方法
- 回調函數
對於剛學的同學,前面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()稱為回調函數。
