package com.sincerity.egg.common.test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 遵循阿里巴巴开发规范
* 运用多线程的时候,要定义好线程的名称和拒绝策略,这样如果线上出问题能很快的定位到是那块代码的问题
* 线程的名字最好是有业务名称,不然不好定位是那块业务出了问题;
* @author zjz
*
*/
public class TestExecutor {
private static ExecutorService pool;
public static void main(String[] args) {
pool = new ThreadPoolExecutor(3, 5, 1000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(5),
new ThreadFactory(){ public Thread newThread(Runnable r) {
return new Thread(r, "createOrder_thread_" + r.hashCode());
}}, new MyRejectedExecutionHandler());
for(int i =0;i<15;i++) {
pool.execute(new Task());
}
pool.shutdown();
}
static class Task implements Runnable{
@Override
public void run() {
try{
Long duration = (long)(Math.random()*20);
System.out.println("Running Task! "+Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(duration);
}catch(Exception e){
e.printStackTrace();
}
}
}
static class MyRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString()+"执行了拒绝策略");
}
}
}