回调接口
public interface AsyncTask<T> {
void task(T t);
}
函数回调
public class Callback01 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("请输入运算【1:加 | 2:减】:");
int key = in.nextInt();
int res = 0;
switch (key) {
case 1: res = add(10, 5); break;
case 2: res = low(10, 5); break;
}
System.out.println(res);
}
public static int add(int a, int b) {
return a + b;
}
public static int low(int a, int b) {
return a - b;
}
}
方法的回调
public class Callback02 {
public static void main(String[] args) {
// 用户输入决定回调的具体功能
Scanner in = new Scanner(System.in);
System.out.println("[1:功能A,2:功能B]");
After after = null;
int key = in.nextInt();
switch (key) {
case 1: after = new A(); break;
case 2: after = new B(); break;
}
// 通过功能类去完成特定功能
ReadFile.read(after);
System.out.println("完事");
}
}
// 功能类
class ReadFile {
// 回调大条件:① ②
// ① 功能类的功能方法的参数为回调接口的接口对象
public static void read(After after) {
// 读取后得到res
String res= "读取的文件文本";
// 读取文本后
// 可能 写入文件 | 打印控制台 | 存储数据库
// 不知道具体怎么做,但一定要做某件事
// ② 在合理的位置利用接口对象回调接口方法将功能的数据结果
// 携带出去提供给接口的具体实现体
after.doSomething(res);
}
}
// 回调接口 中定义回调方法
interface After {
void doSomething(String res);
}
// 定义文件读取完毕不同的功能方向
class A implements After {
@Override
public void doSomething(String res) {
// 黑字打印到控制台
System.out.println(res);
}
}
功能类
public class AsyncReadFile {
// 功能方法:方法中接口类的泛型有功能方法的获取结果类型决定
public static void read(AsyncTask<String> task) {
// 匿名线程对象
new Thread() {
@Override
public void run() {
// 功能的具体过程,若干步
System.out.println("开始读取文件...");
StringBuffer sb = new StringBuffer("结果:");
// 读取一次耗时200ms,将结果评价到可变字符串
for (int i = 0; i < 3; i++) {
long time = System.currentTimeMillis();
while (System.currentTimeMillis() - time < 200) {}
System.out.println("读取中...");
sb.append(i + " ");
}
System.out.println("文件读取完毕~~~");
// 得到功能结果在合适的时候回调接口方法
task.task(new String(sb));
}
}.start(); // 匿名线程对象自调用(自动开启线程)
}
}
public class TestARF {
public static void main(String[] args) {
System.out.println("主线程 -- 逻辑一");
System.out.println("开辟子线程去读取文件");
AsyncReadFile.read(new AsyncTask<String>() {
@Override
public void task(String t) {
// 回调方法回调后,便可以拿到具体的操作结果任何具体操作
System.err.println(t);
}
});
System.out.println("主线程 -- 逻辑二");
}
}