通过Callable接口实现可回调参数的多线程
// ① 实现Callable接口(拥有泛型,call方法的结果决定泛型类型)
// ② 实现Call方法(有throws,有返回值)
public class AsyncReadFile implements Callable<String> {
@Override
public String call() throws Exception {
// 功能的具体过程,若干步
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("文件读取完毕~~~");
// 直接返回功能的结果
return new String(sb);
}
}
public class TestARF {
public static void main(String[] args) {
System.out.println("主线程 -- 逻辑一");
// ③ 生成Callable实现类的对象(任务)
AsyncReadFile task = new AsyncReadFile();
// ④ 生成线程管理pool
ExecutorService pool = Executors.newCachedThreadPool();
// ⑤ 利用pool去管理(提交任务)具体 Callable | Runnable
Future<String> future = pool.submit(task);
String res = null;
try {
res = future.get(); // 当前线程会强行等待该操作
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(res);
// 主动关闭pool
if (future.isDone()) {
pool.shutdown();
}
System.out.println("主线程 -- 逻辑二");
}
}