第一种方式
1、自定义一个线程池配置类
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean("taskExecuter")
public ThreadPoolTaskExecutor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(Integer.MAX_VALUE);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("多线程---");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
}
2、自定义一个service异步处理类
@Component
public class ThreadService {
@Autowired
private ThreadTestDao testDao;
@Async("taskExecuter")
public void updateThread(ThreadTest test) {
testDao.updateThreadData(test);
try {
Thread.sleep(5000);
System.out.println("更新已完成。。。。");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
3、使用
@RestController
@RequestMapping("/thread")
public class ThreadTestController {
@Autowired
private ThreadTestService threadTestService;
@Autowired
private ThreadService threadService;
@PostMapping("/t1")
public void thread1(@RequestBody ThreadTest test) {
threadTestService.insertThreadTest(test);
threadService.updateThread(test);
System.out.println("插入成功。。。。");
}
}
第二种方式
1、引入上面创建线程池类
@Autowired
private ThreadPoolTaskExecutor taskExecuter;
@PostMapping("/t2")
public void thread2(@RequestBody ThreadTest test) throws ExecutionException, InterruptedException {
threadTestService.deleteThreadTest(test);
List<Future> futures = new ArrayList<>();
CountDownLatch latch = new CountDownLatch(50);
List<ThreadTest> threadTests = new ArrayList<>();
ThreadTest newTest = null;
for (int i = 0; i < 50; i++) {
newTest = new ThreadTest();
BeanUtils.copyProperties(test,newTest);
newTest.setUserName(test.getUserName()+i);
newTest.setUserCount(i);
threadTests.add(newTest);
}
for (ThreadTest threadTest : threadTests) {
Future<String> future = taskExecuter.submit(() -> {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
threadTestService.insertThreadTest(threadTest);
return "插入成功";
} catch (InterruptedException e) {
log.info("失败信息",e);
return "";
} finally {
latch.countDown();
}
});
futures.add(future);
}
System.out.println("删除成功。。。。");
latch.await();
for (Future future : futures) {
System.out.println(future.get());
}
}
=====================
AtomicInteger atomicInteger = new AtomicInteger();
第三种方式
@PostMapping("/t3")
public void thread3(@RequestBody ThreadTest test) throws ExecutionException, InterruptedException {
CompletableFuture future1 = CompletableFuture.supplyAsync(() -> {
ThreadTest threadTest = testDao.findThread(1);
return threadTest;
}, taskExecuter);
CompletableFuture future2 = CompletableFuture.supplyAsync(() -> {
ThreadTest threadTest = testDao.findThread(2);
return threadTest;
}, taskExecuter);
CompletableFuture.allOf(future1,future2).get();
System.out.println(future1.get());
System.out.println(future2.get());
}