Java多线程系列--“JUC线程池”05之 线程池原理(四)(三)

2014-11-24 02:45:30 · 作者: · 浏览: 7
llerRunsPolicy 示例
复制代码
1 import java.lang.reflect.Field;
2 import java.util.concurrent.ArrayBlockingQueue;
3 import java.util.concurrent.ThreadPoolExecutor;
4 import java.util.concurrent.TimeUnit;
5 import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
6
7 public class CallerRunsPolicyDemo {
8
9 private static final int THREADS_SIZE = 1;
10 private static final int CAPACITY = 1;
11
12 public static void main(String[] args) throws Exception {
13
14 // 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE),"线程池"的阻塞队列容量为1(CAPACITY)。
15 ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE, 0, TimeUnit.SECONDS,
16 new ArrayBlockingQueue(CAPACITY));
17 // 设置线程池的拒绝策略为"CallerRunsPolicy"
18 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
19
20 // 新建10个任务,并将它们添加到线程池中。
21 for (int i = 0; i < 10; i++) {
22 Runnable myrun = new MyRunnable("task-"+i);
23 pool.execute(myrun);
24 }
25
26 // 关闭线程池
27 pool.shutdown();
28 }
29 }
30
31 class MyRunnable implements Runnable {
32 private String name;
33 public MyRunnable(String name) {
34 this.name = name;
35 }
36 @Override
37 public void run() {
38 try {
39 System.out.println(this.name + " is running.");
40 Thread.sleep(100);
41 } catch (Exception e) {
42 e.printStackTrace();
43 }
44 }
45 }
复制代码
(某一次)运行结果:
复制代码
task-2 is running.
task-3 is running.
task-4 is running.
task-5 is running.
task-6 is running.
task-7 is running.
task-8 is running.
task-9 is running.
task-0 is running.
task-1 is running.