【问题标题】:Why does the scheduler kill my shuffling algorithm?为什么调度程序会杀死我的洗牌算法?
【发布时间】:2019-06-12 03:54:19
【问题描述】:

我想出了这个算法,用于将随机用户随机分配给其他用户。 (对于秘密圣诞老人游戏)但是当我在给定时间启动异步进程以进行洗牌时,它会在第 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);

}

【问题讨论】:

  • 你怎么知道那是调度器?
  • 嗯,这个方法在没有调度器的情况下也可以工作,我测试过了。
  • 为什么您的 LocalDateTime 被硬编码为 1 月 17 日?
  • 又是一次测试 - 昨天是 1 月 17 日。

标签: spring-boot spring-mvc asynchronous scheduled-tasks shuffle


【解决方案1】:

所以经过深度调试发现其实我的算法不对,被调度器杀死是正常的。这是我所做的更改:

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;
}

【讨论】:

  • 很高兴您发现了您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
相关资源
最近更新 更多