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

2014-11-24 02:45:30 · 作者: · 浏览: 1
new ArrayBlockingQueue(CAPACITY));
17 // 设置线程池的拒绝策略为"DiscardOldestPolicy"
18 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
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 pool.shutdown();
27 }
28 }
29
30 class MyRunnable implements Runnable {
31 private String name;
32 public MyRunnable(String name) {
33 this.name = name;
34 }
35 @Override
36 public void run() {
37 try {
38 System.out.println(this.name + " is running.");
39 Thread.sleep(200);
40 } catch (Exception e) {
41 e.printStackTrace();
42 }
43 }
44 }
复制代码
运行结果:
task-0 is running.
task-9 is running.
结果说明:将"线程池的拒绝策略"由DiscardPolicy修改为DiscardOldestPolicy之后,当有任务添加到线程池被拒绝时,线程池会丢弃阻塞队列中末尾的任务,然后将被拒绝的任务添加到末尾。
3. AbortPolicy 示例
复制代码
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.AbortPolicy;
6 import java.util.concurrent.RejectedExecutionException;
7
8 public class AbortPolicyDemo {
9
10 private static final int THREADS_SIZE = 1;
11 private static final int CAPACITY = 1;
12
13 public static void main(String[] args) throws Exception {
14
15 // 创建线程池。线程池的"最大池大小"和"核心池大小"都为1(THREADS_SIZE),"线程池"的阻塞队列容量为1(CAPACITY)。
16 ThreadPoolExecutor pool = new ThreadPoolExecutor(THREADS_SIZE, THREADS_SIZE, 0, TimeUnit.SECONDS,
17 new ArrayBlockingQueue(CAPACITY));
18 // 设置线程池的拒绝策略为"抛出异常"
19 pool.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
20
21 try {
22
23 // 新建10个任务,并将它们添加到线程池中。
24 for (int i = 0; i < 10; i++) {
25 Runnable myrun = new MyRunnable("task-"+i);
26 pool.execute(myrun);
27 }
28 } catch (RejectedExecutionException e) {
29 e.printStackTrace();
30 // 关闭线程池
31 pool.shutdown();
32 }
33 }
34 }
35
36 class MyRunnable implements Runnable {
37 private String name;
38 public MyRunnable(String name) {
39 this.name = name;
40 }
41 @Override
42 public void run() {
43 try {
44 System.out.println(this.name + " is running.");
45 Thread.sleep(200);
46 } catch (Exception e) {
47 e.printStackTrace();
48 }
49 }
50 }
复制代码
(某一次)运行结果:
复制代码
java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1774)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:768)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:656)
at AbortPolicyDemo.main(AbortPolicyDemo.java:27)
task-0 is running.
task-1 is running.
复制代码
结果说明:将"线程池的拒绝策略"由DiscardPolicy修改为AbortPolicy之后,当有任务添加到线程池被拒绝时,会抛出RejectedExecutionException。
4. Ca