1.线程池配置类
package com.example.demo.asyn;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncTask{
public static ThreadPoolTaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(40);
taskExecutor.setQueueCapacity(100);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy() );
taskExecutor.initialize();
return taskExecutor;
}
public static void asyncTask(Runnable asyncTask) {
getAsyncExecutor().execute(asyncTask);
}
}
2.Servcie业务类
package com.example.demo.asyn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@Autowired
private AsynExcuet asynExcuet;
@Autowired
private TestService testService;
public void text(String s){
System.out.println("kaishi");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(s);
}
}
3.线程调用service
package com.example.demo.asyn;
public class AsynService implements Runnable{
private TestService testService;
private String s;
public AsynService(TestService testService, String s) {
this.testService = testService;
this.s = s;
}
@Override
public void run() {
testService.text(s);
}
}
4.Controller类
package com.example.demo.contrller;
import com.example.demo.asyn.AsynService;
import com.example.demo.asyn.AsyncTask;
import com.example.demo.asyn.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestContller {
@Autowired
private TestService testService;
@GetMapping("/test")
public String test(String s){
if(s.equals("1")){
testService.text(s);
} else {
AsynService asynService = new AsynService(testService,s);
AsyncTask.asyncTask(asynService);
}
return s;
}
}