public void startWork() { while (!leader.isDone() && avaiableList.size() > 0) { for (String type : DanceTask.typeList) { List<Follower> unavaiableList = new ArrayList<>(); for (Follower follower : avaiableList) { if (follower.isDone() || follower.cannotAcceptFollower(leader)) { unavaiableList.add(follower); continue; } leader.invite(follower, type); } avaiableList.removeAll(unavaiableList); } } this.isDone = true; }
public boolean cannotAcceptFollower(Leader leader) { int count = 0; for (String key : list.keySet()) { if (leader.getId() == list.get(key).getId()) { count++; } if (count >= 2) { return true; } } return false; }
private static void startInvite(int leaderNumber, int followerNumber) throws InterruptedException { CountDownLatch latch = new CountDownLatch(leaderNumber); List<Leader> leaders = new ArrayList<>(); for (int i = 0; i < leaderNumber; i++) { leaders.add(new Leader(i)); } List<Follower> followers = new ArrayList<>(); for (int i = 0; i < followerNumber; i++) { followers.add(new Follower(i)); } ExecutorService executorService = Executors.newFixedThreadPool(followerNumber); List<InviteThread> threads = new ArrayList<>(); for (Leader leader : leaders) { InviteThread inviteThread = new InviteThread(leader, followers); // inviteThread.startWork(); executorService.submit(inviteThread); threads.add(inviteThread); } while (true) { int count = 0; for (InviteThread thread : threads) { if (thread.isDone()) { count++; } } if (count == threads.size()) { break; } Thread.sleep(1000L); } executorService.shutdown(); for (Leader leader : leaders) { leader.print(); } }