回调方法接口
先添加一个回调方法接口
/**
* 回调接口
*/
public interface CallBack {
/**
* 回调函数
*
* @param result
*/
void call(String result);
}
调用方
多线程调用具体处理逻辑方法,和回调函数的具体实现,默认有10次处理,当数量增大的时候存在线程安全问题
/**
* 调用方
* 实现回调接口
*/
public class Caller implements CallBack {
//用于计数
private int length, count;
/**
* 构造函数
*/
public Caller() {
length = 10;
count = 0;
}
/**
* 要调用的Deal方法的函数,模拟length条线程进行处理
*/
public void deal() {
Executor dev = new Executor();
for (int i = 0; i < length; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
//调用具体逻辑,传入此对象
dev.deal(Caller.this, finalI);
}
}).start();
}
}
/**
* 回调函数处理逻辑,等所有线程处理完,进行后续逻辑处理
*
* @param result
*/
public void call(String result) {
synchronized (Caller.class) {
//输出执行状态
System.out.println(result);
length--;
count++;
System.out.println("执行线程数量统计=" + count);
if (length == 0) {
System.out.println("所有线程执行完毕");
}
}
}
}
被调用方
执行具体的处理逻辑,并回调方法,通知调用方自己执行完成
/**
* 执行方
* 调用回调函数
*/
public class Executor {
/**
* 处理逻辑
* 并调用回调方法
*
* @param callBack
* @param index
*/
public void deal(CallBack callBack, int index) {
System.out.println("第" + index + "条线程开始执行");
//随机数模拟方法执行一段时间
long m = new Random().nextInt(5);
try {
Thread.sleep(m * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("sleep异常");
}
String result = "第" + index + "条线程执行完成,执行" + m + "秒";
//执行完成调用回调函数
callBack.call(result);
}
}
测试程序
/**
* 测试类
*
* @author will
*/
public class CallBackTest {
public static void main(String[] args) {
Caller master = new Caller();
master.deal();
}
}
执行结果
参考:https://blog.csdn.net/jim1451/article/details/84036930