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 }
时间: 2024-10-20 10:44:45