나는 1000 단어의 단어 목록을 가지고 있습니다. 가장 많이 발생하는 것부터 가장 적은 것으로 나열해야합니다.Java에서 스레드로 목록 정렬
처럼 :
Dog, 100 times
Cat, 50 times
Fish, 40 times
Monkey, 10 times
Bird, 10 times
Camel, 10 times
.
.
.
Lion, 1 times
Tiger, 1 times
내가 이런 짓을하고 while 루프와 함께 작동하지만, 10 초처럼 걸리는 작업의 다음 부분은 스레드를 사용하여 적은 시간에 정렬을 확인하는 것입니다. 나는 5 개의 쓰레드를 사용할 계획이다. 나는 그것들을 사용할 수 있고, 개별적으로 달릴 수있다. Thread1은 1-200을, Thread2는 201-400을, Thread3는 401-600을 정렬 할 수 있다고 말하지만, 결국에는 5 개의 다른리스트를 가질 것이다. ? Thread1 목록에 10 개의 Dog가 있고 Thread2 목록에 20 개의 Dog가 있습니다 ... 콘솔에 혼합되어 있습니다 ... 위 예제에서 5 Threads를 사용하고 싶습니다. 가능합니까? 좀 팁을 주시겠습니까, 나는 실에 익숙하지 않습니다.
편집 : 내장 정렬 기능을 사용하고 있습니다. 사용중인 정렬 알고리즘은 중요하지 않습니다. 이 작업은 최상의 정렬 알고리즘을 사용하는 것이 아니라 스레드를 사용하여 정렬하는 것입니다.
코드 :
//This is the list
ArrayList<String> animalList = new ArrayList<String>();
//This is the map from the list
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : animalList) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
//This is the final map
TreeMap<String, Integer> sortedMap = sortMapByValue(map);
public static TreeMap<String, Integer> sortMapByValue(Map<String, Integer> map){
Comparator<String> comparator = new ValueComparator(map);
TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
result.putAll(map);
return result;
}
public class ValueComparator implements Comparator<String>{
HashMap<String, Integer> map = new HashMap<String, Integer>();
public ValueComparator(Map<String, Integer> map2){
this.map.putAll(map2);
}
@Override
public int compare(String s1, String s2) {
if(map.get(s1) >= map.get(s2)){
return -1;
}else{
return 1;
}
}
}
어떤 정렬 알고리즘입니까? 멀티 스레딩으로 속도를 높이 려하지 않고 최적화하기위한 첫 번째 장소 일 수 있습니다. – copeg
이 방법은 100 초 근처에서 수행해야합니다.당신은 어딘가에서 매우 비효율적 인 무언가를하고 있습니다. – Cruncher
@Cruncher Im은 고양이와 개를 정렬하지 않으려 고합니다 ... 100은 단지 예일뿐입니다. – Anarkie