Я создал asyn c configurer для создания методов asyn c, например:
package backendApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
return executor;
}
}
И затем определил свой метод asyn c:
package backendApplication.model;
import backendApplication.model.dao.TourService;
import backendApplication.model.entities.Scheduling;
import backendApplication.model.entities.Tour;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
@Service
public class SwapManager {
@Autowired
TourService tourService;
@Async("threadPoolTaskExecutor")
public CompletableFuture addSchedule(Scheduling scheduling){
long finishesIn = scheduling.getDate().getTime() - new Date().getTime();
System.out.println(finishesIn);
try {
Thread.sleep(finishesIn);
Tour t = scheduling.getTour();
t.removeActive(scheduling);
t.addFinished(scheduling);
tourService.save(t);
System.out.println("completou o schedule");
return CompletableFuture.completedFuture(null);
} catch (InterruptedException e) {
e.printStackTrace();
}
return CompletableFuture.completedFuture(null);
}
}
И я вызываю свой метод asyn c в контроллере следующим образом:
@RequestMapping(value = "/createScheduling/{idTour}", method = RequestMethod.POST)
public ResponseEntity<HttpStatus> createSchedulings(@PathVariable(value="idTour") String id, @RequestBody List<Scheduling> schedulings) {
try{
// Get tour
Tour tour = tourService.get(Integer.parseInt(id));
System.out.println(Arrays.toString(schedulings.toArray()));
for (Scheduling s : schedulings){
// Associate tour and save scheduling
s.setPaid(true);
s.setTour(tour);
schedulingService.save(s);
// Save scheduling active on tour
tour.addActive(s);
tourService.save(tour);
// Add schedule to swap manager
System.out.println("Adicionou schedule");
swapManager.addSchedule(s);
}
}catch (Exception ex) {
return new ResponseEntity<> (HttpStatus.NOT_ACCEPTABLE);
}
return new ResponseEntity<> (HttpStatus.CREATED);
}
Но после времени ожидания поток переходит с java .lang.Thread.State: TIMED_WAITING (спящий) на java .lang.Thread.State: WAITING (парковка) без выполнения кода под строкой Thread.sleep ().
Кто-нибудь может объяснить мне, почему?