Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.locks.ReentrantLock;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.TimeUnit;
- class Demonstration {
- public static void main(String[] args) throws Exception {
- DeferredCallback deferredCallback = new DeferredCallback();
- Set<Thread> allThreads = new HashSet<Thread>();
- Thread service =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- deferredCallback.executeCallback();
- } catch (InterruptedException ie) {
- }
- }
- });
- service.start();
- for (int i = 0; i < 3; i++) {
- final int index = i;
- Thread thread =
- new Thread(
- () -> {
- Callback callback = new Callback(3000 - index * 1000, Thread.currentThread().getName());
- deferredCallback.scheduleCallback(callback);
- });
- thread.setName("Thread_" + i);
- thread.start();
- allThreads.add(thread);
- Thread.sleep(100);
- }
- for (Thread thread : allThreads) {
- thread.join();
- }
- }
- }
- class DeferredCallback {
- private final PriorityQueue<Callback> callbackQueue =
- new PriorityQueue<Callback>(
- new Comparator<Callback>() {
- public int compare(Callback c1, Callback c2) {
- return (int) (c1.executeAt - c2.executeAt);
- }
- });
- private final ReentrantLock lock = new ReentrantLock();
- private final Condition condition = lock.newCondition();
- public DeferredCallback() {}
- public void executeCallback() throws InterruptedException {
- while (true) {
- lock.lock();
- while (callbackQueue.isEmpty()) {
- condition.await();
- }
- // Now queue has something
- while (!callbackQueue.isEmpty()) {
- long latestScheduleTime = computeLatestScheduleTime();
- if (latestScheduleTime <= 0) {
- break;
- }
- condition.await(latestScheduleTime, TimeUnit.MILLISECONDS);
- }
- Callback callback = callbackQueue.poll();
- System.out.println(
- "Executed at: "
- + System.currentTimeMillis()
- + " Requested at: "
- + callback.executeAt
- + " Message: "
- + callback.message);
- lock.unlock();
- }
- }
- private long computeLatestScheduleTime() {
- return (callbackQueue.peek().executeAt - System.currentTimeMillis());
- }
- public void scheduleCallback(Callback callback) {
- lock.lock();
- callbackQueue.add(callback);
- condition.signal();
- lock.unlock();
- }
- }
- class Callback {
- final long executeAt;
- final String message;
- Callback(long executeAfterMillis, String message) {
- this.executeAt = System.currentTimeMillis() + executeAfterMillis;
- this.message = message;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement