Java--线程池
package util; public abstract class Runnable implements java.lang.Runnable { private int priority; public Runnable() { this.priority = 0; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public static void main(String[] args) { String libname = System.mapLibraryName(""); } }
import java.util.Timer; import java.util.TimerTask; /** * 被观察者,每秒钟通知观察者检查任务 * * @author guoxiaoming * */ public class TimerObserver extends java.util.Observable { public static TimerObserver instance = new TimerObserver(); public static long now = System.currentTimeMillis(); public static Timer timer; // 每秒钟都会通知观察者检查自己的任务是否可以开始执行 public TimerObserver() { timer = new Timer("schedule-task"); timer.schedule(new TimerTask() { public void run() { now = scheduledExecutionTime(); instance.setChanged(); instance.notifyObservers(); } }, 0, 1000); } }
import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import util.Runnable; /** * 观察者对象,保存着任务集合,被观察者每1s钟通知观察者检查任务 确实也可能出现后添加的任务可能比先添加的任务先执行 * * @author guoxiaoming * */ public class TimerTask implements Observer { private class TaskPair { private Runnable runnable; private long waitSeconds; public TaskPair(Runnable runnable, long waitSeconds) { this.runnable = runnable; this.waitSeconds = waitSeconds; } } public long elapse = 0; public static SortedMap<Long, LinkedList<TaskPair>> taskList = Collections .synchronizedSortedMap(new TreeMap<Long, LinkedList<TaskPair>>()); public TimerTask() { TimerObserver.instance.addObserver(this); } @Override public synchronized void update(Observable o, Object arg) { Set<Map.Entry<Long, LinkedList<TaskPair>>> entrySet = taskList .entrySet(); Iterator<Map.Entry<Long, LinkedList<TaskPair>>> iter = entrySet .iterator(); elapse++; while (iter.hasNext()) { Map.Entry<Long, LinkedList<TaskPair>> entry = iter.next(); LinkedList<TaskPair> linkedTask = entry.getValue(); Iterator<TaskPair> itertask = linkedTask.iterator(); while (itertask.hasNext()) { TaskPair task = itertask.next(); if (task.waitSeconds > elapse) { break; } ThreadPool.addTask(task.runnable); itertask.remove(); } if (linkedTask.size() == 0)// linkedTask.isEmpty() { iter.remove(); } } } // 其实两个方法可以合并成一个方法的 每个LinkedList当中的任务都是后添加的在前面 public synchronized void addTask(Runnable runnable, long waitSeconds) { LinkedList<TaskPair> ll = taskList.get(waitSeconds); if (ll == null) { ll = new LinkedList<TaskPair>(); taskList.put(waitSeconds,ll); } synchronized (ll) { // 此处应该使用addLast而不是addFirst ll.addLast(new TaskPair(runnable, waitSeconds + elapse)); } } }
import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.Map.Entry; import util.Runnable; //线程池 public class ThreadPool implements java.lang.Runnable { // key 优先级 value 线程列表 private static SortedMap<Integer, LinkedList<Runnable>> tasks = Collections.synchronizedSortedMap(new TreeMap<Integer, LinkedList<Runnable>>()); private int priority; private static int task_count; private static Object task_count_locker = new Object(); private static long time_lastAdd; // 记录各个优先级线程管理的任务数,本身管理线程也算是一个任务 private static SortedMap<Integer, Integer> count = new TreeMap<Integer, Integer>(); private ThreadPool(int priority) { this.priority = priority; synchronized (count) { Integer c = count.get(priority); count.put(priority, c == null ? 1 : c.intValue() + 1); } } @Override public void run() { for (;;) { try { Runnable r = null; LinkedList<Runnable> ll = tasks.get(priority); synchronized (ll) { if (ll.isEmpty()) { ll.wait(); } r = ll.removeLast(); synchronized (task_count_locker) { task_count--; } } r.run(); } catch(Exception ex) { ex.printStackTrace(); } } } // 添加新的线程 public static void addThread(int priority) { if (tasks.get(priority) == null) { tasks.put(priority, new LinkedList<Runnable>()); new Thread(new ThreadPool(priority), "thread---" + priority).start(); } } // 添加新的任务 静态方法中只能使用静态变量 非静态方法中可以使用静态变量 public static void addTask(Runnable runnable) { int prior = runnable.getPriority(); LinkedList<Runnable> ll = tasks.get(prior); if (ll == null) { System.out.println("no match priority thread"); return; } synchronized (ll) { synchronized (task_count_locker) { task_count++; } ll.add(runnable);// 其实addFirst还是add区别不大 time_lastAdd = System.currentTimeMillis(); ll.notify(); } } // 得到一个映射拷贝 public static Map<Integer, Integer> getTaskCounts() { SortedMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); synchronized (count) { for (Iterator<Integer> iter = tasks.keySet().iterator(); iter.hasNext();) { Integer prior = iter.next(); map.put(prior, tasks.get(prior).size()); } // 或者 for (Entry<Integer, LinkedList<Runnable>> iter : tasks.entrySet()) { map.put(iter.getKey(), iter.getValue().size()); } // 再或者使用繁琐的while循环 // Set<Map.Entry<Integer,LinkedList<Runnable>>> } return map; } public static long getTaskTotal() { synchronized (task_count_locker) { return task_count; } } }
import util.Runnable; public class MainTest { public static void main(String[] args) throws InterruptedException { // 添加1-10 10个优先级的管理线程 for (int i = 1; i <= 10; i++) { ThreadPool.addThread(i); } TimerTask timerTask = new TimerTask(); for (int i = 1; i <= 10; i++) { timerTask.addTask(new RunnableTask(i), i); } } static class RunnableTask extends Runnable { public RunnableTask(int priority) { super.setPriority(priority); } @Override public void run() { int begin = (super.getPriority() - 1) * 10; int end = super.getPriority() * 10; for (int i = begin; i <= end; i++) { System.out.print(i + " "); } System.out.println(); } } }
0 1 2 3 4 5 6 7 8 9 10 10 11 12 13 14 15 16 17 18 19 20 20 21 22 23 24 25 26 27 28 29 30 30 31 32 33 34 35 36 37 38 39 40 40 41 42 43 44 45 46 47 48 49 50 50 51 52 53 54 55 56 57 58 59 60 60 61 62 63 64 65 66 67 68 69 70 70 71 72 73 74 75 76 77 78 79 80 80 81 82 83 84 85 86 87 88 89 90 90 91 92 93 94 95 96 97 98 99 100