write a java program for a multithreaded voting system where:
Votes are cast for candidates by their names. Multiple threads simulate voting by
casting votes for various candidates concurrently.
Each vote involves a small artificial delay(Thread.sleep(3000) to simulate the time
it takes for network requests or database operations to complete. This increases
the likelihood of concurrent access issues.
You need to track the total votes for each candidate in a thread-safe manner.
After all threads finish, display the candidates sorted by the number of votes
received in descending order.
import java.util.*;
import java.util.concurrent.*;
public class VotingSystem {
// A thread-safe map to store candidates and their vote counts
private static final ConcurrentHashMap<String, Integer> voteCounts = new
ConcurrentHashMap<>();
// List of candidates
private static final List<String> candidates = Arrays.asList("Alice", "Bob",
"Charlie", "David");
// Simulate a voting thread
static class VotingThread extends Thread {
private final String candidate;
public VotingThread(String candidate) {
this.candidate = candidate;
}
@Override
public void run() {
try {
// Simulate network delay
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Increment the vote count for the candidate in a thread-safe manner
voteCounts.merge(candidate, 1, Integer::sum);
}
}
public static void main(String[] args) throws InterruptedException {
// Create a pool of threads to simulate concurrent voting
ExecutorService executorService = Executors.newFixedThreadPool(10);
// Simulate voting by submitting voting tasks for different candidates
for (int i = 0; i < 100; i++) {
String candidate = candidates.get((int) (Math.random() *
candidates.size()));
executorService.submit(new VotingThread(candidate));
}
// Wait for all threads to finish
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
// Sort the candidates based on vote count in descending order
List<Map.Entry<String, Integer>> sortedVotes = new
ArrayList<>(voteCounts.entrySet());
sortedVotes.sort((entry1, entry2) ->
entry2.getValue().compareTo(entry1.getValue()));
// Display the results
System.out.println("Voting Results:");
for (Map.Entry<String, Integer> entry : sortedVotes) {
System.out.println(entry.getKey() + ": " + entry.getValue() + "
votes");
}
}
}
output:
Voting Results:
Bob: 29 votes
David: 29 votes
Alice: 22 votes
Charlie: 20 votes