我想出了一种将该随机用户改组为其他用户的算法。 (用于秘密圣诞老人游戏)但是当我在给定的时间启动用于改组的异步过程时,它会被第5个用户停止。有什么想法吗?
我对算法的服务并启动它:
public class GitfteeServiceImpl implements GifteeService{
@Autowired
private UserRepository userRepository;
private final ScheduledExecutorService shufflingScheduler = Executors.newSingleThreadScheduledExecutor();
@Override
public void setGifteeToAll() {
List<User> users = userRepository.findAll();
List<User> usersGiftees = userRepository.findAll();
List<Long> userIds = usersGiftees.stream().map(User::getUserId).collect(Collectors.toList());
log.info(users.toString());
for(User u : users){
User giftee = getGifteeForOne(u, usersGiftees,userIds);
userIds.remove(giftee.getUserId());
usersGiftees.remove(giftee);
}
}
private User getGifteeForOne(User user, List<User> users, List<Long> ids) {
Long randomId = getRandomId(ids);
User giftee = userRepository.findByUserId(randomId);
while (giftee == null || !users.contains(giftee) || Objects.equals(user.getUserId(), randomId)){
randomId = getRandomId(ids);
giftee = userRepository.findByUserId(randomId);
}
user.setGiftee(giftee);
userRepository.save(user);
return giftee;
}
private Long getRandomId(List<Long> ids) {
Collections.shuffle(ids);
return ids.get(0);
}
@Override
public void scheduleShuffling(LocalDateTime gameDuration) {
Runnable scheduleShufflingTask = this::setGifteeToAll;
Duration duration = Duration.between(LocalDateTime.now(), gameDuration);
shufflingScheduler.schedule(scheduleShufflingTask, duration.getSeconds(), TimeUnit.SECONDS);
}
}
这是我的控制者:
public class AdminController {
@Autowired
GifteeService gifteeService;
@PostMapping("/start_date")
public void hi(@RequestBody LocalDateTime localDateTime) {
LocalDateTime aDateTime = LocalDateTime.of(2019, Month.JANUARY, 17, 22, 39, 50);
gifteeService.scheduleShuffling(aDateTime);
}
答案 0 :(得分:0)
因此,在进行深度调试之后,我发现我的算法实际上是不正确的,并且被调度程序杀死是正常的。这是我所做的更改:
private User getGifteeForOne(User user, List<User> users, List<Long> ids) {
Long randomId = getRandomId(ids);
User giftee = userRepository.findByUserId(randomId);
//The line that was incorrect
while (giftee == null || users.contains(giftee) || Objects.equals(user.getUserId(), randomId)){
randomId = getRandomId(ids);
giftee = userRepository.findByUserId(randomId);
}
user.setGiftee(giftee);
userRepository.save(user);
return giftee;
}