Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Random;
- class CustomThread extends Thread {
- private static Map<Character, Integer> globalCharDictionary = new HashMap<>();
- private final static Object monitor = new Object();
- private static synchronized void incrementGlobalCharDictionary(Map<Character, Integer> charDictionary) {
- if (globalCharDictionary.size() == 0) {
- String asciiLowercase = Main.getASCIILowercaseArray();
- for (char ch : asciiLowercase.toCharArray()) {
- globalCharDictionary.put(ch, 0);
- }
- }
- for (Map.Entry<Character, Integer> characterIntegerEntry : charDictionary.entrySet()) {
- Character key = characterIntegerEntry.getKey();
- Integer value = characterIntegerEntry.getValue();
- Integer globalValue = globalCharDictionary.get(key);
- globalCharDictionary.put(key, (globalValue + value));
- }
- }
- private int charCount;
- private char[] charArray;
- private Random rand = new Random();
- CustomThread(int charCount, String charArray) {
- this.charCount = charCount;
- this.charArray = charArray.toCharArray();
- }
- private Character getRandomChar(char[] charArray){
- return charArray[rand.nextInt(charArray.length)];
- }
- @Override
- public void run() {
- Map<Character, Integer> charDictionary = new HashMap<>();
- for (char ch : charArray) {
- charDictionary.put(ch, 0);
- }
- for (int k = 0; k < charCount; k++) {
- Character randCh = getRandomChar(charArray);
- int chNumber = charDictionary.get(randCh);
- charDictionary.put(randCh, ++chNumber);
- }
- incrementGlobalCharDictionary(charDictionary);
- }
- }
- public class Main{
- final static int [] allCharsCount = {100, 1000, 10000, 100000, 150000, 250000, 500000, 1000000, 5000000, 10000000, 15000000,
- 20000000, 25000000, 30000000, 35000000, 40000000, 45000000, 50000000, 60000000,
- 100000000, 500000000, 1000000000, 2000000000};
- final static int threadCount = 64;
- public static String getASCIILowercaseArray()
- {
- String answer = "";
- char c;
- for (c = 'a'; c <= 'z'; c++)
- {
- answer += c;
- }
- return answer;
- }
- public static void main(String[] args) throws InterruptedException {
- String asciiLowercase = getASCIILowercaseArray();
- for (int i : allCharsCount) {
- int threadCapacity = i/threadCount;
- ArrayList<CustomThread> threadArray = new ArrayList<>();
- long start = System.currentTimeMillis();
- for (int j = 0; j < threadCount; j++) {
- threadArray.add(new CustomThread(threadCapacity, asciiLowercase));
- }
- for (CustomThread thread : threadArray) {
- thread.start();
- }
- for (CustomThread thread : threadArray) {
- thread.join();
- }
- long finish = System.currentTimeMillis();
- long timeConsumedMillis = finish - start;
- System.out.println("For " + i + " chars needs " + timeConsumedMillis + " milliseconds");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement