Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package angel;
- import java.util.HashMap;
- import java.util.Map;
- public class RandomCounterMap extends Thread {
- private int start;
- private int end;
- private long executionTime;
- private Map<Integer, Integer> results;
- public RandomCounterMap(int start, int end) {
- this.start = start;
- this.end = end;
- this.results = new HashMap<>();
- }
- public Map<Integer, Integer> getResults() {
- return results;
- }
- public int getLength() {
- int length = 0;
- for (int value : results.values()) {
- length += value;
- }
- return length;
- }
- public long getExecutionTime() {
- return executionTime;
- }
- private int randomInt() {
- return (int) (Math.random() * 100);
- }
- @Override
- public void run() {
- long startTime = System.currentTimeMillis();
- for (int i = start; i <= end; i++) {
- int result = randomInt();
- try {
- results.put(result, results.get(result) + 1);
- } catch (NullPointerException e) {
- results.put(result, 1);
- }
- }
- long endTime = System.currentTimeMillis();
- executionTime = endTime - startTime;
- }
- public static void main(String[] args) {
- int numbers = 100_000_000;
- int numThreads = 1;
- int numbersPerThread = numbers / numThreads;
- RandomCounterMap[] calculators = new RandomCounterMap[numThreads];
- for (int i = 0; i < numThreads; i++) {
- int start = i * numbersPerThread + 1;
- int end = (i + 1) * numbersPerThread;
- calculators[i] = new RandomCounterMap(start, end);
- }
- long startTime = System.currentTimeMillis();
- for (RandomCounterMap calculator : calculators) {
- calculator.start();
- }
- for (RandomCounterMap calculator : calculators) {
- try {
- calculator.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- long endTime = System.currentTimeMillis();
- System.out.println("Time taken: " + (endTime - startTime) + "ms");
- int totalResults = 0;
- for (int i = 0; i < calculators.length; i++) {
- System.out.println("Thread " + i + " took " + calculators[i].getExecutionTime() + "ms");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement