线程池中的线程的排序问题

 1 package org.zln.thread.poolqueue;
 2 
 3 import org.slf4j.Logger;
 4 import org.slf4j.LoggerFactory;
 5 
 6 import java.util.Comparator;
 7 import java.util.UUID;
 8 import java.util.concurrent.*;
 9 
10 /**
11  * 线程池中的线程的排序问题
12  * Created by sherry on 16/11/4.
13  */
14 public class StringThread {
15 
16     /**
17      * 日志
18      */
19     private static Logger logger = LoggerFactory.getLogger(StringThread.class);
20 
21     public static void main(String[] args) {
22         ExecutorService executorService = new StringExecutorPool(10).getExecutorService();
23         for (int i = 0; i < 100; i++) {
24             logger.debug(String.valueOf(i));
25             executorService.execute(new StringHandler(System.nanoTime()));
26         }
27         executorService.shutdown();
28         logger.debug("停止");
29     }
30 
31 
32 }
33 
34 /**
35  * 任务类
36  */
37 class StringHandler implements Runnable {
38 
39     public long time;
40 
41     public StringHandler(long time) {
42         this.time = time;
43     }
44 
45     @Override
46     public void run() {
47         System.out.println(Thread.currentThread().getName() + ":" + UUID.randomUUID().toString());
48     }
49 }
50 
51 /**
52  * 线程池
53  */
54 class StringExecutorPool {
55     private int poolSize;
56     private BlockingQueue<Runnable> blockingQueue;
57     private ExecutorService executorService;
58 
59     public StringExecutorPool(int poolSize) {
60         this.poolSize = poolSize;
61         blockingQueue = new PriorityBlockingQueue<>(100, new Comparator<Runnable>() {
62             @Override
63             public int compare(Runnable o1, Runnable o2) {
64                 int res = o1.hashCode() - o2.hashCode();
65                 if (res == 0){
66                     StringHandler stringHandler1 = (StringHandler) o1;
67                     StringHandler stringHandler2 = (StringHandler) o2;
68                     res = (int) (stringHandler1.time - stringHandler2.time);
69                 }
70                 if (res >0 ){
71                     System.out.println("往后排");
72                 }else if (res < 0){
73                     System.out.println("往前排");
74                 }else{
75                     System.out.println("排不出");
76                 }
77                 return res;
78             }
79 
80         });
81 
82         executorService = new ThreadPoolExecutor(poolSize, poolSize,
83                 0L, TimeUnit.MILLISECONDS,
84                 blockingQueue);
85     }
86 
87     public ExecutorService getExecutorService() {
88         return executorService;
89     }
90 }

 

转载于:https://www.cnblogs.com/sherrykid/p/6031932.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值