`

向线程传递数据的三种方法

阅读更多
1.通过构造函数传递,这种很简单当传递参数少的时候可用。
2.通过类中定义一系列的public的方法或变量(也可称之为字段)。然后在建立完对象后,通过对象实例逐个赋值。
private String name;       
public void setName(String name)      
{          
    this.name = name;      } 

这也比较常见
3.通过回调函数传递数据
package thread;

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方法被称为回调函数。从本质上说,回调函数就是事件函数。在Windows API中常使用回调函数和调用API的程序之间进行数据交互。因此,调用回调函数的过程就是最原始的引发事件的过程。在这个例子中调用了process方法来获得数据也就相当于在run方法中引发了一个事件。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics