class util{privatestaticfinalStringCHARACTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";publicstaticStringgenerateString(int length){// No need to worry about thread-safeStringBuilder stringCreator =newStringBuilder();// more randomSecureRandom random =newSecureRandom();for(int i =0; i < length; i++){
stringCreator.append(CHARACTERS.charAt(random.nextInt(CHARACTERS.length())));}return stringCreator.toString();}}
线程池多线程创建随机字符串
privatefinalExecutorService executorService =Executors.newFixedThreadPool(10);privateArrayList<String>yieldStrings(int size)throwsInterruptedException,ExecutionException{var resutlList =newArrayList<String>();// List<String> synchronizedList = Collections.synchronizedList(resutlList);ArrayList<Future<String>> futures =newArrayList<>();// we need the returned value so it is callable but runnableCallable<String> task =()->GenerateUtil.generateString(10);for(int i =0; i < size; i++){Future<String> future = executorService.submit(task);
futures.add(future);}Instant begin =Instant.now();// if the task didn't finished, we will block in the get method// only we really get the result, we can put it into collectionfor(var ele : futures){String tmp = ele.get();
resutlList.add(tmp);}Instant end =Instant.now();// remember to shutdown thread-pool or u will...
executorService.shutdown();System.out.println(resutlList.size()+" Words by Generating Strings Time Consuming: "+Duration.between(begin, end).toMillis()+" MS");return resutlList;}