一、单线程统计
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
public class wc1 {
public static void main(String[] args) {
Map<String,Integer> map = new TreeMap<>();
try {
BufferedReader buff = new BufferedReader(new FileReader("word.txt"));
String tmp = "";
while ((tmp=buff.readLine())!=null){
if(!tmp.equals("")){
String[] strs = tmp.trim().split(" ");
for (int i = 0; i < strs.length; i++) {
if(map.containsKey(strs[i])){
map.put(strs[i],map.get(strs[i])+1);
}else {
map.put(strs[i],1);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
map.forEach((k,v)->{
System.out.println("单词:"+k+":"+v);
});
}
}
二、多线程统计
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class wc2 {
static Map<String,Map<String,Integer>> threadMap = new ConcurrentHashMap<>();
static ExecutorService executorService = Executors.newCachedThreadPool();
public static void threadConf(String content,Integer count){
wcThread wcThread = new wcThread(content);
Thread thread = new Thread(wcThread);
executorService.execute(thread);
threadMap.put("thread-"+count,wcThread.wordMap);
}
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("word.txt"));
String tmpStr = "";
StringBuffer lineStringBuf = new StringBuffer();
int num = 0;
while ((tmpStr=br.readLine())!=null){
if(!tmpStr.equals("")){
num++;
lineStringBuf.append(tmpStr.trim()+" ");
if(num%30000==0){
threadConf(lineStringBuf.toString(),num/30000);
lineStringBuf.delete(0,lineStringBuf.length());
}
}
}
if(lineStringBuf.length()>0){
threadConf(lineStringBuf.toString(),0);
lineStringBuf.delete(0,lineStringBuf.length());
}
executorService.shutdown();
while (true){
if(executorService.isTerminated()){
ConcurrentHashMap<String, Integer> chMap = new ConcurrentHashMap<>();
for (Map<String, Integer> value : threadMap.values()) {
value.forEach((k,v)->{
if(chMap.containsKey(k)){
chMap.put(k,chMap.get(k)+value.get(k));
}else {
chMap.put(k,value.get(k));
}
});
}
chMap.forEach((k,v)->{
System.out.println("单词:"+k+":"+v);
});
break;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class wcThread implements Runnable{
String content = "";
Map<String,Integer> wordMap = new TreeMap<>();
public wcThread(String content) {
this.content = content;
}
@Override
public void run() {
String[] strs = content.trim().split(" ");
for (int i = 0; i < strs.length; i++) {
if(wordMap.containsKey(strs[i])){
wordMap.put(strs[i],wordMap.get(strs[i])+1);
}else {
wordMap.put(strs[i],1);
}
}
}
}