/**
* 最小堆
*/
public class MyPriorityQueue {
private int[] arr;
private int capacity;
private int size=0;
ReentrantLock lock=new ReentrantLock();
Condition notEmpty=lock.newCondition();
Condition notFull=lock.newCondition();
public MyPriorityQueue(int capacity) {
this.arr = new int[capacity];
this.capacity = capacity;
}
void add(Integer e) {
lock.lock();
try{
while (size==capacity)notFull.await();
arr[size++] = e;
int t = size - 1;
int parent;
while (t > 0&&arr[parent = (t - 1) >>> 1] > arr[t]) {
swap(t,parent);
t = parent;
}
if (size<capacity){
notFull.signalAll();
}
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
} finally {
lock.unlock();
}
}
int poll() {
lock.lock();
try{
while (size==0)notFull.await();
int root = arr[0];
arr[0] = arr[--size];
int left = 0, right = 0, t = 0;
while (true) {
left = (t<<1) + 1;
right = (t<<1) + 2;
if (left > size-1) {
break;
}
if (left==size-1){
if (arr[left]<arr[t]){
swap(t,left);
}
break;
}
int min = arr[left] < arr[right] ? left : right;
if (arr[min] > arr[t]) {
break;
}
swap(t,min);
t = min;
}
if (size>0){
notEmpty.signalAll();
}
return root;
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
// 创建一个优先级阻塞队列
MyPriorityQueue queue = new MyPriorityQueue(3);
// 启动生产者线程
for (int i = 0; i < 3; i++) {
int producerId = i;
new Thread(() -> {
for (int j = 0; j < 5; j++) {
try {
// 生成任务,优先级为随机值
int task=(int) (Math.random() * 10);
// System.out.println("Producer " + producerId + " produced task: " + task);
queue.add(task); // 将任务放入队列
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
// 启动消费者线程
for (int i = 0; i < 2; i++) {
int consumerId = i;
new Thread(() -> {
while (true) {
try {
int task = queue.poll(); // 从队列中取出任务
System.out.println("Consumer " + consumerId + " consumed task: " + task);
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
private void swap(int i, int j) {
int tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}
手写简易PriorityQueue
最新推荐文章于 2025-11-09 15:57:51 发布
1121

被折叠的 条评论
为什么被折叠?



