优先级队列,PriorityQueue是有优先级.
阻塞队列.也是特殊的队列,虽然是先进先出,但也具有特殊功能.
阻塞:
如果队列为空,执行出队列操作,就会阻塞,阻塞到另一个线程往 队列里添加元素
如果队列已满,执行入操作,就会阻塞,阻塞到另一个线程从队列中取走元素.
Queue提供的三个方法:
入队列:offer 2.出队 poll 3.取首元素:peek
阻塞队列方法有两个:
1.入队列 :put 2.出队列:take
用于消费者和生产者模型代码来展示:
需要注意的重点:
保证原子 性,用锁.
用while循环代替if循环,为了确保二次if的进行,直接用while代替.
wait()保证循环阻塞.
package thread;
//1.实现队列
//保证线程安全,得加锁.
class MyBlockingQueue {
private int[] arry = new int[100];
private int size = 0;
private int head = 0;
private int tail = 0;
public void put(int values) {
synchronized (this) {
while (size == arry.length) {
//队列满了,不能继续插入,产生阻塞
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
arry[tail] = values;
tail++;
if (tail >= arry.length) {
tail = 0;
}
size++;
//唤醒take中的take.
this.notify();
}
}
public Integer take() {
int count;
synchronized (this) {
while (size == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count = arry[head];
head++;
if (head >= arry.length) {
head = 0;
}
size--;
//唤醒put中的wait()
this.notify();
}
return count;
}
}
public class ThreadDemo23 {
public static void main(String[] args) {
/*MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
myBlockingQueue.put(1);
myBlockingQueue.put(2);
myBlockingQueue.put(3);
myBlockingQueue.put(4);
int result = myBlockingQueue.take();
int result1 = myBlockingQueue.take();
int result2 = myBlockingQueue.take();
int result3 = myBlockingQueue.take();
System.out.println(result3);*/
MyBlockingQueue queue=new MyBlockingQueue();
Thread customer=new Thread(()->{
while (true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Integer result = queue.take();
System.out.println("消费者;"+result);
}
});
customer.start();
Thread productor=new Thread(()->{
int count=0;
while (true){
System.out.println("生产者:"+count);
queue.put(count);
count++;
}
});
productor.start();
}
}