packagecom;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.Executor;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.LinkedBlockingQueue;importjava.util.concurrent.ScheduledExecutorService;importjava.util.concurrent.ThreadPoolExecutor;importjava.util.concurrent.TimeUnit;public classdemo3 {public static voidmain(String[] args) {//TODO Auto-generated method stub//test1();//test2();
test3();
}static voidtest1(){//ExecutorService的用法
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);for( int i=0;i<100;i++){
fixedThreadPool.execute(newRunnable(){public voidrun() {
System.out.println("====threadId="+Thread.currentThread().getId());
}
}
);
}
}static voidtest2(){
Executor exec=newThreadPerTaskExecutor();
exec.execute(newRunnable(){
@Overridepublic voidrun() {//TODO Auto-generated method stub
System.out.println("ccccc"+Thread.currentThread().getId());
}
});
}//ThreadPoolExecutor
static voidtest3(){
BlockingQueue queue = new LinkedBlockingQueue();
ThreadPoolExecutor threadPool= new ThreadPoolExecutor(2, 4, 5, TimeUnit.SECONDS,
queue,newThreadPoolExecutor.AbortPolicy());for(int i=0;i<100;i++){
threadPool.execute(new MyThread(i+""));
}
threadPool.shutdown();
}static class MyThread implementsRunnable {privateString name;publicMyThread(String name) {this.name =name;
}
@Overridepublic voidrun() {//做点事情
try{
Thread.sleep(1000);
System.out.println(name+"===当前线程="+Thread.currentThread().getId() + " finished job!") ;
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}//execute的用法
class ThreadPerTaskExecutor implementsExecutor {public voidexecute(Runnable r) {newThread(r).start();
}
}