创建Job
import java.util.concurrent.Future;
public interface AsyncService {
/**
* 多线程下载
* 这是一个带有回调的多线程函数
*
* @param url 下载url
* @param savePath 下载路径
* @return
*/
Future<String> downloadFileJob(String url, String savePath);
}
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
@Service
public class AsyncServiceImpl implements AsyncService{
@Async
@Override
public Future<String> downloadFileJob(String url, String savePath) {
// 模拟下载耗时任务
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 模拟完成任务后返回参数
String result = "任务完成";
return new AsyncResult<>(result);
}
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@EnableAsync
@SpringBootTest
public class ApplicationTests {
@Autowired
private AsyncService asyncService;
@Test
public void test() throws InterruptedException, ExecutionException {
// 异步任务列表
List<Future<String>> jobList = new ArrayList<>();
// 多线程跑任务
long start = System.currentTimeMillis();
// 执行批量任务
for (int i = 1; i <= 200; i++) {
jobList.add(asyncService.downloadFileJob("https://xxx.com", "/temp/file/"));
}
// 查看整批任务是否执行完毕
for (Future<String> job : jobList) {
// 使用Future的isDone()方法返回该方法是否执行完成,如果异步方法全部执行完,跳出循环
while (!job.isDone()) {
Thread.sleep(100);// 每隔100毫秒看一下是否执行完毕了
}
// get()方法获取异步任务返回值
String result = job.get();
System.out.println("多线程执行job返回内容:" + result);
}
long end = System.currentTimeMillis();
System.out.println("多线程执行总耗时:" + (end - start) / 1000 + "s");
// 单线程跑任务
start = System.currentTimeMillis();
for (int i = 1; i <= 200; i++) {
new AsyncServiceImpl().downloadFileJob("https://xxx.com", "/temp/file/");
}
end = System.currentTimeMillis();
System.out.println("单线程执行总耗时:" + (end - start) / 1000 + "s");
}
}
ref
https://blog.csdn.net/z1353095373/article/details/108225310