/*
*作者:呆萌老师
*☑csdn认证讲师
*☑51cto高级讲师
*☑腾讯课堂认证讲师
*☑网易云课堂认证讲师
*☑华为开发者学堂认证讲师
*☑爱奇艺千人名师计划成员
*在这里给大家分享技术、知识和生活
*各种干货,记得关注哦!
*/
在传统的同步开发模式下,当我们调用一个函数时,通过这个函数的参数将数据传入,并通过这个函数的返回值来返回最终的计算结果。但在多线程的异步开发模式下,数据的传递和返回和同步开发模式有很大的区别。由于线程的运行和结束是不可预料的,因此,在传递和返回数据时就无法象函数一样通过函数参数和return语句来返回数据。
代码实现
数据对象创建。
public class Data {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public class SubThread extends Thread{
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public SubThread()
{
}
public SubThread(Data data)
{
this.data=data;
}
public void run()
{
System.out.println("子线程内:"+data.getValue());
this.data.setValue(200); //将值做修改
Test.callback(); //调用回调函数
}
}
public class Test {
static boolean flag=false;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Data data=new Data();
data.setValue(20);
System.out.println("调用子线程前,值为"+data.getValue());
//第一种传值方式 通过构造函数传值
//SubThread subThread=new SubThread(data);
SubThread subThread=new SubThread();
//第二种传值方式 通过属性赋值
subThread.setData(data);
subThread.start();
//第三种方式 使用回调函数
while(!flag);
System.out.println("调用子线程后,值为"+data.getValue());
}
public static void callback()
{
flag=true;
}
}
更多了解
https://edu.51cto.com/course/20124.html