【多线程】Java多线程中线程间的数据传递

线程间的数据传递主要分为向线程传递参数和从线程获取返回值;

1、 向线程中传递参数的方法主要有三种:
    通过构造函数传递 在调用start方法之前通过线程类的构造方法将数据传入线程。
public class MyThread 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 MyThread("world");
	   thread.start();        
	 }
}
    通过变量和方法传递
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();
    }
}
    调用回调函数传递数据
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();
    }
}
从本质上说,回调函数就是事件函数;在这个例子中调用了process方法来获得数据也就相当于在run方法中引发了一个事件。
2、从线程中获取返回值的方法主要有:
    使用join()方法
public class MyThread3 extends Thread {
          
   
    private String value1;
    private String value2;

    public void run() {
          
   
        value1 = "value1";
        value2 = "value2";
    }

    public static void main(String[] args) throws Exception {
          
   
        MyThread3 thread = new MyThread3();
        thread.start();
        thread.join();
        System.out.println("value1:" + thread.value1);
        System.out.println("value2:" + thread.value2);
    }
}
在thread.join()执行完后,也就是说线程thread已经结束了;因此,在thread.join()后面可以使用MyThread类的任何资源来得到返回数据。
    使用回调函数 与前边介绍的一致,灵活运用即可。
经验分享 程序员 微信小程序 职场和发展