按照公平原则执行任务
创始人
2024-08-24 02:30:21
0

可以使用Java中的ConcurrentLinkedQueue作为任务队列,每个任务都可以封装成一个Runnable对象,然后在另一个线程中执行这些任务。为了按照公平原则执行任务,可以在队列中使用Iterator遍历任务,并且为每个任务设置一个权重值,权重越高的任务会被先执行。

示例代码如下:

import java.util.Comparator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class FairTaskExecutor {

  private final ConcurrentLinkedQueue tasks = new ConcurrentLinkedQueue<>();
  private final AtomicInteger sequence = new AtomicInteger(0);

  /**
   * 添加任务到队列
   * @param task 任务
   * @param priority 权重值
   */
  public void addTask(Runnable task, int priority) {
    taskPriority = sequence.getAndIncrement() * 100 + priority;
    tasks.add(new PriorityRunnable(task, taskPriority));
  }

  /**
   * 执行任务
   */
  public void executeTasks() {
    Runnable task;
    while ((task = tasks.poll()) != null) {
      task.run();
    }
  }

  /**
   * 带有优先级的Runnable
   */
  private class PriorityRunnable implements Runnable, Comparable {
    private final Runnable task;
    private final int priority;

    public PriorityRunnable(Runnable task, int priority) {
      this.task = task;
      this.priority = priority;
    }

    @Override
    public void run() {
      task.run();
    }

    @Override
    public int compareTo(PriorityRunnable other) {
      return Integer.compare(priority, other.priority);
    }
  }

}

使用示例:

// 创建任务执行器
FairTaskExecutor executor = new FairTaskExecutor();

// 添加任务
executor.addTask(() -> System.out.println("Task 1 - Low Priority"), 1);
executor.addTask(() -> System.out.println("Task 2 - High Priority"), 10);
executor.addTask(() -> System.out.println("Task 3 - Medium Priority"), 5);

// 按照公平原则执行任务
executor.executeTasks();
``

相关内容

热门资讯

最新消息!wepoker作必弊... 最新消息!wepoker作必弊视频,微信小程序微乐内蒙破解器,普及透视(真实有挂)-哔哩哔哩1、玩家...
透视揭露!wpk有作必弊吗,w... 透视揭露!wpk有作必弊吗,wpk私人局有透视吗(透视)其实存在有教程(哔哩哔哩)1、下载好透视辅助...
透视总结!wpk作必弊,微乐科... 透视总结!wpk作必弊,微乐科技软件下载,解密脚本(有挂教程)-哔哩哔哩1、实时wpk作必弊透视辅助...
脚本曝光!wejoker辅助软... 脚本曝光!wejoker辅助软件价格,wepoker破解器有用吗(透视)原来存在有脚本(哔哩哔哩)1...
透视黑科技!哈糖大菠萝助手,微... 透视黑科技!哈糖大菠萝助手,微信微乐小程序辅助器免费安装,开挂脚本(详细教程)-哔哩哔哩1)哈糖大菠...
据悉!WePoKer辅助器,微... 据悉!WePoKer辅助器,微乐小程序免费黑科技,关于脚本(今日头条)-哔哩哔哩在进入WePoKer...
透视详细!aapoker发牌逻... 透视详细!aapoker发牌逻辑,aapoker透视脚本下载(透视)确实是真的教程(哔哩哔哩)1. ...
透视好友房!wepoker有插... 透视好友房!wepoker有插件吗,微乐家乡麻辣自建房,总结透视(有挂技巧)-哔哩哔哩在进入wepo...
脚本透视!wpk俱乐部怎么作必... 脚本透视!wpk俱乐部怎么作必弊,wpk系统是否存在作必弊行为(透视)总是真的是有插件(哔哩哔哩)1...
今天上午!拱趴大菠萝万能挂图解... 今天上午!拱趴大菠萝万能挂图解,微乐家乡自建房辅助app,了解脚本(有挂方法)-哔哩哔哩拱趴大菠萝万...