map
import java.util.*;
public class teachermap{
public static void main(String[] args){
//Set text in a string
String text = "Good morning.Having a good class.";
//Creat a TreeMap to hold words as key and count as value
TreeMap <String,Integer> map = new TreeMap<String,Integer> ();
String[] words = text.split("[ \n\t\r.,;:!?(){}]");
for(int i=0;i<words.length;i++){
String key = words[i].toLowerCase();
if(words[i].length()>1){
if(map.get(key)==null) map.put(key,1);
else{
int value = map.get(key).intValue();
value++;
map.put(key,value);
}
}
}
//Get all entries into a set
Set <Map.Entry<String,Integer>> entrySet = map.entrySet();
//Get key and value from the each entry
for(Map.Entry<String,Integer> entry:entrySet)
System.out.println(entry.getValue()+"\t"+entry.getKey());
}
}
thread pool
import java.util.concurrent.*;
public class ExecutorDemo {
public static void main(String[] args) {
// Create a fixed thread pool with maximum three threads执行器创建三个线程来并发执行三个
ExecutorService executor = Executors.newFixedThreadPool(3);
// Submit runnable tasks to the executor
executor.execute(new PrintChar('a', 100));
executor.execute(new PrintChar('b', 100));
executor.execute(new PrintNum(100));
// Shut down the executor
executor.shutdown();
}
}
如果将第5行改成 ExecutorService executor = Executors.newFixedThreadPool(1);
这三个任务将顺次执行,因为在线程池中只有一个线程。
如果改成ExecutorService executor = Executors.newFixedThreadPool();
为每个等待的人物任务创建一个新的线程,所以,所有的任务都并发地执行。
thread using lock
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class AccountWithSyncUsingLock {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
// Create and launch 100 threads
for (int i = 0; i < 100; i++) {
executor.execute(new AddAPennyTask());
}
executor.shutdown();
// Wait until all tasks are finished
while (!executor.isTerminated()) {
}
System.out.println("What is balance ? " + account.getBalance());
}
// A thread for adding a penny to the account
public static class AddAPennyTask implements Runnable {
public void run() {
account.deposit(1);
}
}
// An inner class for account
public static class Account {
private static Lo