public class 自定义线程创建 {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(2,
5,
0,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(2),
new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread t=new Thread(r);
System.out.println("Creat");
return t;
}
},
// new ThreadPoolExecutor.AbortPolicy());//第一种拒绝策略:直接抛出异常AbortPolicy
new ThreadPoolExecutor.CallerRunsPolicy());//第二种拒绝策略:新建一个线程
// new ThreadPoolExecutor.DiscardOldestPolicy());//第三种拒绝策略:在队列里推出一个最早的
// new ThreadPoolExecutor.DiscardPolicy());//第四种:直接丢弃。
// new RejectedExecutionHandler() {
// public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
// System.out.println(Thread.currentThread().getName() + "被抛弃了");
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName() + "拒绝成功");
//
// }
// });//第种:直接丢弃。
for (int i = 0; i < 10; i++) {
final int finalI = i;
threadPoolExecutor.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+"开始"+ finalI);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"结束"+ finalI); }
});
}
}
}