ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 生产者消费者模型 生产者生产数据到缓冲区中,消费者从缓冲区中取数据。 如果缓冲区已经满了,则生产者线程阻塞; 如果缓冲区为空,那么消费者线程阻塞。 ~~~ public interface ITaskQueue{ public void add(); public int remove(); } public class Consumer extends Thread{ ITaskQueue queue; public Consumer(ITaskQueue queue){ this.queue = queue; } public void run(){ while(true){ try { Thread.sleep((long) (1000 * Math.random())); } catch (InterruptedException e) { e.printStackTrace(); } queue.remove(); } } } public class Producer extends Thread{ ITaskQueue queue; public Producer(ITaskQueue queue){ this.queue = queue; } public void run(){ while(true){ try { Thread.sleep((long) (1000 * Math.random())); } catch (InterruptedException e) { e.printStackTrace(); } queue.add(); } } ~~~ ## 使用synchronized wait notify ~~~ public void TaskQueue1 implements ITaskQueue{ //当前资源数量 private int num = 0; //资源池中允许存放的资源数目 private int size = 10; public synchronized void add(){ if(num >= size){ wait(); }else{ num ++; notifyAll(); } } public synchronized void remove(){ if(num <= 0){ wait(); }else{ num --; notifyAll(); } } } ~~~ ## 使用BlockingQueue ~~~ public void TaskQueue2 implements ITaskQueue{ private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(); public void add(){ queue.put(1); } public void remove(){ queue.talke(); } } ~~~