import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* java 线程池实例
* @author lixin
*/
public class Test {
public static void main(String[] args) {
//采用固定大小线程池
ExecutorService exe = Executors.newFixedThreadPool(2);
//要处理的数据
Map<String, String> map = new HashMap<String, String>();
map.put("a", "aaaa");
map.put("b", "bbbb");
map.put("c", "cc");
map.put("d", "d");
map.put("e", "e");
String m;
int i = 0;
for(Entry<String, String> entry: map.entrySet()) {
m=entry.getValue();
//调用线程池
exe.execute(new MyThread(i,exe,m));
i++;
}
}
}
class MyThread implements Runnable
{
int id;
ExecutorService exe;
//m即实例对象
String m = "";
MyThread(int id, ExecutorService exe,String m) {
this.exe = exe;
this.id = id;
this.m = m;
}
public void run() {
//业务处理
System.out.println("exe info:" + exe.toString()+"start");
try {
Thread.sleep(5000L);
} catch (Exception e) {
System.out.println(e);
}
System.out.println(id + "end");
}
}