自定义同步、非同步延时队列【java】

文章展示了如何使用Java实现一个延时队列,包括一个非同步和一个同步阻塞版本。队列基于环形数组实现,具有添加、删除和检查元素的方法。同步版本使用ReentrantLock和Condition来处理阻塞和唤醒等待的线程。测试代码创建了生产者和消费者线程,模拟添加带延迟的消息并消费它们。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 延时队列的关键抽象方法
import java.util.concurrent.TimeUnit;

public interface MyDelayed {

    long getDelay(TimeUnit unit);
}
/**
  * 队列的抽象接口
  */
public interface MyQueue<E> {

    boolean add(E e) throws Exception;

    E take() throws Exception;

    E peek();

    void clear();

    boolean isEmpty();

    int getSize();

}
// 自定义环形数组,线程安全由上游保证
public class RingArray<E> {
    private Object[] element;
    private int head, tail, size, capacity;

    RingArray(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.head = -1;
        this.tail = 0;
        element = new Object[capacity];
    }

    public void addToTail(E ele) {
        if(size < capacity) {
            head = (head + 1) == capacity ? 0 : head + 1;
            element[head] = ele;
            size ++;
        }
    }

    public E removeFromTail() {
        E ele = null;
        if(size > 0) {
            ele = (E)element[tail];
            element[tail] = null;
            tail = (tail + 1) == capacity ? 0 : tail + 1;
            size --;
        }
        return ele;
    }

    public void clear() {
        for (int i = 0; i < capacity; i ++) element[i] = null;
    }

    public E peek() {
        return (E) element[tail];
    }

    public int getSize() {
        return size;
    }

    public void print() {
        for (int i = 0; i < capacity; i ++) {
            if(element[i] != null) System.out.print(element[i] + ", ");
        }
        System.out.println();
    }

    @Override
    public String toString() {
        return this.size + " from " + this.head + " to " + this.tail;
    }

}
// 延时队列的抽象类,提供了一些模板方法
import java.util.concurrent.locks.ReentrantLock;

public abstract class MyAbstractQueue<E> implements MyQueue<E> {

    private final RingArray<E> array;
    private final int capacity;

    private final ReentrantLock lock = new ReentrantLock();

    public MyAbstractQueue(int capacity) {
        this.capacity = capacity;
        array = new RingArray(capacity);
    }

    public RingArray<E> getArray() {
        return array;
    }

    public ReentrantLock getLock() {
        return lock;
    }

    public int getCapacity() {
        return capacity;
    }

    @Override
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return array.peek();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void clear() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            array.clear();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public boolean isEmpty() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return getSize() == 0;
        } finally {
            lock.unlock();
        }
    }

    @Override
    public int getSize() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return array.getSize();
        } finally {
            lock.unlock();
        }
    }

}
// 一个非同步的延时队列
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class MyDelayQueueWithoutSyn<E extends MyDelayed> extends MyAbstractQueue<E> {

    public MyDelayQueueWithoutSyn(int capacity) {
        super(capacity);
    }

    public boolean add(E e) {
        final ReentrantLock lock = getLock();
        lock.lock();
        try {
            getArray().addToTail(e);
        } finally {
            lock.unlock();
        }
        return true;
    }

    public E take() {
        final ReentrantLock lock = getLock();
        lock.lock();
        try {
            E first = peek();
            if(first == null) {
                return null;
            } else {
                for (;;) {
                    if (first.getDelay(TimeUnit.NANOSECONDS) <= 0) {
                        return getArray().removeFromTail();
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

}
//同步阻塞延时对列实现
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyDelayQueueWithSyn<E extends MyDelayed> extends MyAbstractQueue<E> {

    private Condition fullCondition = getLock().newCondition();
    private Condition emptyCondition = getLock().newCondition();

    public MyDelayQueueWithSyn(int capacity) {
        super(capacity);
    }

    public boolean add(E e) throws Exception {
        final ReentrantLock lock = getLock();
        lock.lock();
        try {
            while (getSize() == getCapacity()) {
                fullCondition.await();
            }
            getArray().addToTail(e);
            emptyCondition.signalAll();
        } finally {
            lock.unlock();
        }
        return true;
    }

    public E take() throws Exception {
        final ReentrantLock lock = getLock();
        lock.lock();
        try {
            while (getSize() == 0) {
                emptyCondition.await();
            }
            fullCondition.signalAll();
            for (;;) {
                if (peek().getDelay(TimeUnit.NANOSECONDS) <= 0) {
                    return getArray().removeFromTail();
                }
            }
        } finally {
            lock.unlock();
        }
    }


}
// 测试方法
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 自定义延时队列
 *      同步延时队列
 *      非同步延时队列
 */
public class MyDelayQueueTest {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        //MyDelayQueueWithoutSyn queue = new MyDelayQueueWithoutSyn(10);
        MyDelayQueueWithSyn queue = new MyDelayQueueWithSyn(10);
        ExecutorService producer = Executors.newFixedThreadPool(2, new MyThreadFactory());
        for(int i = 0; i < 100; i ++) {
            final int index = i;
            int mod = index % 2;
            int random = new Random().nextInt(5);
            final long deadLine = mod == 0 ? 250 * random : 500 * random;
            producer.submit(() -> {
                Message<Integer> m = new Message<>(index, deadLine);
                try {
                    queue.add(m);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }

        ExecutorService consumer = Executors.newSingleThreadExecutor();
        consumer.submit(() -> {
            while (!queue.isEmpty()) {
                try {
                    System.out.println("get => " + queue.take());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        producer.shutdown();
        consumer.shutdown();

        System.out.println(System.currentTimeMillis() - start);
    }

    static class MyThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        }

    }

    static class Message<T> implements MyDelayed {

        long deadLine;

        T t;

        Message(T t, long deadLine) {
            this.t = t;
            setDeadLine(deadLine);
        }

        public void setDeadLine(long deadLine) {
            this.deadLine = deadLine + System.currentTimeMillis();
        }

        public long getDeadLine() {
            return deadLine;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return deadLine - System.currentTimeMillis();
        }

        @Override
        public String toString() {
            return "Message{" +
                    "deadLine=" + deadLine +
                    ", t=" + t +
                    '}';
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

x_pengcheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值