阻塞队列:
当队列为空时,获取操作是阻塞的;当队列为满时,添加操作是阻塞的
判断是否满足阻塞条件,并用条件变量阻塞
加锁,同一时刻只有一个线程进行操作(put/get);
package MutileThread;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class RResource3{
Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();
private int defaultSize;
private Queue<Integer>q;
private List<Integer> outList;
public RResource3(Queue<Integer>q,List<Integer>outList,int size)
{
this.q = q;
this.outList = outList;
this.defaultSize = size;
}
public List<Integer> getOutList() {
return outList;
}
public void put(int data)
{
try {
lock.lock();
while (q.size()==defaultSize)
{
System.out.println("队列满了");
c1.await();
}
q.offer(data);
System.out.println(String.format("Thread :%s, put data %d",Thread.currentThread().getName(),data));
c2.signalAll();
}catch (InterruptedException e)
{
e.printStackTrace();
}finally {
lock.unlock();
}
}
public int get()
{
int t=0;
try {
lock.lock();
if (q.size()==0)
{
System.out.println("队列为空");
c2.await();
}
t = q.poll();
System.out.println(String.format("data: %d out",t));
outList.add(t);
Collections.sort(outList);
c1.signalAll();
}catch (InterruptedException e)
{
e.printStackTrace();
}finally {
lock.unlock();
return t;
}
}
}
public class RRun3 {
public static void main(String[]args) throws InterruptedException{
RResource3 rResource3 = new RResource3(new LinkedList<>(), new CopyOnWriteArrayList<>(), 5);
CountDownLatch countDownLatch = new CountDownLatch(20);
new Thread(() -> {
for (int i = 0; i < 10; i++) {
countDownLatch.countDown();
rResource3.put(i);
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
countDownLatch.countDown();
int t = rResource3.get();
}
}, "B").start();
countDownLatch.await();
for (int l : rResource3.getOutList()) {
System.out.println(l);
}
}
}

本文深入探讨了阻塞队列的工作原理,包括其在队列满或空时的阻塞特性,以及如何使用条件变量和锁来确保线程安全。通过具体代码示例,展示了在多线程环境中,如何实现生产者和消费者模型。
170万+

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



