生产-消费者模式
<h1>生产-消费者模式</h1>
<p>这段代码在很多讲述生产者-消费者模式的地方都会用到,其中,Producer线程首先启动,synchronized关键字使其能够获得queue的锁,其他线程处于等待状态。初始queue为空,通过offer向缓冲区队列写入数据,notify()方法使得等待该缓冲区queue的线程(此处为消费者线程)唤醒,但该线程并不能马上获得queue的锁,只有等生产者线程不断向queue中写入数据直到queue.size() == size,此时缓冲队列充满,生产者线程调用wait()方法进入等待状态。此时,消费者线程处于唤醒并且获得queue的锁,通过poll()方法消费缓冲区中的数据,同理,虽然调用了notify()方法使得生产者线程被唤醒,但其并不能马上获得queue的锁,只有等消费者线程不断消费数据直到queue.size() == 0,消费者线程调用wait()方法进入等待状态,生产者线程重新获得queue的锁,循环上述过程,从而完成生产者线程与消费者线程的协作。</p>
<pre><code class="language-java">import java.util.PriorityQueue;
public class TestWait {
private static final String TAG = &quot;TestWait&quot;;
private int size = 5;
private PriorityQueue&lt;Integer&gt; queue = new PriorityQueue&lt;Integer&gt;(size);
public static void main(String[] args) {
TestWait test = new TestWait();
Producer producer = test.new Producer();
Consumer consumer = test.new Consumer();
producer.start();
consumer.start();
}
class Consumer extends Thread {
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == 0) {
try {
System.out.println(&quot;队列空,等待数据&quot;);
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
queue.notify();
}
}
queue.poll(); // 每次移走队首元素
queue.notify();
System.out.println(&quot;从队列取走一个元素,队列剩余&quot; + queue.size() + &quot;个元素&quot;);
}
}
}
}
class Producer extends Thread {
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == size) {
try {
System.out.println(&quot;队列满,等待有空余空间&quot;);
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
queue.notify();
}
}
queue.offer(1); // 每次插入一个元素
queue.notify();
System.out.println(&quot;向队列取中插入一个元素,队列剩余空间:&quot;
+ (size - queue.size()));
}
}
}
}
}
</code></pre>