码迷,mamicode.com
首页 > 编程语言 > 详细

线程池优先队列Demo

时间:2015-07-12 14:12:24      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

 1 package Thread;
 2 
 3 import org.junit.BeforeClass;
 4 import org.junit.Test;
 5 
 6 import java.util.concurrent.*;
 7 
 8 /**
 9  * Created by csophys on 15/7/12.
10  */
11 public class ThreadPoolExecutorTest {
12     private static ThreadPoolExecutor threadPoolExecutor;
13 
14     private static BlockingQueue blockingQueue;
15 
16     @BeforeClass
17     public static void setBeforeClass() {
18         //优先队列
19         blockingQueue = new PriorityBlockingQueue();
20         threadPoolExecutor = new ThreadPoolExecutor(1, 100, 10, TimeUnit.MINUTES, blockingQueue);
21     }
22 
23 
24     @Test
25     public void testExecuteThrowThreadPool() {
26         System.out.println("观察控制台输出的值是否有序");
27         threadPoolExecutor.execute(new Task(5));
28         threadPoolExecutor.execute(new Task(14));
29         threadPoolExecutor.execute(new Task(6));
30         threadPoolExecutor.execute(new Task(19));
31         threadPoolExecutor.execute(new Task(20));
32         threadPoolExecutor.execute(new Task(10));
33     }
34 }
35 
36 class Task implements Runnable, Comparable<Task> {
37     private int value = 0;
38 
39     public Task(int value) {
40         this.value = value;
41     }
42 
43     public void run() {
44         System.out.println(value);
45         value++;
46     }
47 
48     /**
49      * 实现compareTo()方法。它接收其他事件作为参数,并且比较当前事件与参数的优先级。
50      * 如果当前事件的优先级更大,则返回-1,如果这两个优先级相等,则返回0,如果当前事件的优先级更小,则返回1。
51      * 注意,这与大多数Comparator.compareTo()的实现是相反的。
52      */
53 
54     public int compareTo(Task task) {
55         return this.value - task.value;
56     }
57 }

 

线程池优先队列Demo

标签:

原文地址:http://www.cnblogs.com/csophys/p/4640883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!