整体思路
class Node {
int type;// 定时任务还是一次性任务
int interval;// 定时任务的时间间隔
long time;//任务执行的具体时间
Runnable task;
}
class ConcurrentSortedList {
add() {
// TODO notify Timer Thread
}
}
class Timer {
ExecutorService exe;
ConcurrentSortedList list;//线程安全的有序列表
int interval;
work() {
while (true) {
Node node;
if (list.isNotEmpty() && (node == list.getTail()) != null) {
if (node.time + interval >= System.currentTimeMillis()) { //已经到达最后一个节点的预定时间,获取尾节点,并执行任务
exe.submit(node.task);
list.revomeTail();
if (node.type == 定时任务) { //如果是定时任务,生成新节点并插入到list中
long interval = node.interval;
node = new Node();
node.time = System.currentTimeMillis() + interval;
list.add(node);
}
}
else { // 最后一个节点还没有到达执行时间, 控制线程等待
Thread.sleep(interval);
}
}
else {
LockSupport.park(this);
}
}
}
}
ConcurrentSortedList:
public class ConcurrentSortedList<T> {
private final Node<T> head;
private final Node<T> tail;
private Node<T> iterator;
private Comparator<T> comparator;
public ConcurrentSortedList(Comparator<T> comparator) {
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
iterator = head;
this.comparator = comparator;
}
public void insert(T value) {
Node current = head;
current.lock.lock();
Node<T> next = current.next;
try {
while (true) {
next.lock.lock();
try {
if (next == tail || comparator.compare(value, next.value) <= 0) {
Node node = new Node(value, current, next);
next.prev = node;
current.next = node;
return;
}
} finally {
current.lock.unlock();
}
current = next;
next = current.next;
}
} finally {
next.lock.unlock();
}
}
public Node<T> removeFirst() {
head.lock.lock();
try {
if (tail != head.next) {
Node result = head.next;
result.lock.lock();
Node next = result.next;
next.lock.lock();
try {
remove(result);
} finally {
next.lock.unlock();
result.lock.unlock();
}
return result;
}
}
finally {
head.lock.unlock();
}
return null;
}
private void remove(Node node) {
Node prev = node.prev;
Node next = node.next;
prev.next = next;
next.prev = prev;
node.next = null;
node.prev = null;
}
public List<T> getAll() {
List<T> result = new ArrayList<T>();
try {
head.lock.lock();
try {
while (iterator.next != tail) {
iterator.next.lock.lock();
iterator = iterator.next;
}
iterator = head;
while (iterator.next != tail) {
result.add(iterator.next.value);
iterator = iterator.next;
}
}
finally {
iterator = head;
while (iterator.next != tail) {
iterator.next.lock.unlock();
iterator = iterator.next;
}
iterator = head;
}
}
finally {
head.lock.unlock();
}
return result;
}
}
class Node<T> {
T value;
Node<T> prev;
Node<T> next;
ReentrantLock lock = new ReentrantLock();
Node() {
}
Node(T value, Node prev, Node next) {
this.value = value;
this.prev = prev;
this.next = next;
}
}