模型图
执行代码:
生产类
`_/
`` ``编程实现生产者线程,不断地生产产品
`` ``/
_public classProduceThread extendsThread {**<br />** //声明一个仓库类型的引用作为成员变量,是为了能调用调用仓库类中的生产方法 合成复用原则``privateStoreHouse storeHouse;``//为了确保两个线程共用同一个仓库``publicProduceThread(StoreHouse storeHouse) {`**<br />**` this.storeHouse = storeHouse; }`**
``@Override<br />`` ``public void ``run``() {``while ``(``true``) {``storeHouse``.produceProduct()``;<br />`` try ``{Thread.``_sleep_``(``1000``)``;<br />`` ``} ``catch ``(InterruptedException e) {e.printStackTrace()``;<br />`` ``}}}}
消费类
**public class **``**ConsumerThread **``**extends **``**Thread {**** **``**// **``**声明一个仓库类型的引用作为成员变量,是为了能调用调用仓库类中的生产方法 合成复用原则<br />**``** **``**private **``**StoreHouse **``**storeHouse**``**;<br />**``** **``**// **``**为了确保两个线程共用同一个仓库<br />**``** **``**public **``**ConsumerThread**``**(StoreHouse storeHouse) {**** **``**this**``**.**``**storeHouse **``**= storeHouse**``**;<br />**``** **``**}**<br />`** **@Override** **public void **run**() {<br /> **while **(**true**) {<br /> **storeHouse**.consumerProduct()**;<br />** try **{**`<br />`** Thread.**sleep**(**100**)**;** **} **catch **(InterruptedException e) {<br /> e.printStackTrace()**;<br />** `**}**** }**** }****}**
仓库类
**/* **``**编程实现仓库类**``** */<br />**``**public class **``**StoreHouse {**** **``**private int **``**cnt **``**= **``**0**``**; **``**// **``**用于记录产品的数量<br />**``** **``**public synchronized void **``**produceProduct**``**() {**** notify()**``**;<br />**``** if **``**(**``**cnt **``**< **``**10**``**) {**** System.**``**_out_**``**.println(**``**"**``**线程**``**" **``**+ Thread.**``**_currentThread_**``**().getName() + **``**"**``**正在生产第**``**" **``**+ (**``**cnt**``**+**``**1**``**) + **``**"**``**个产品**``**..."**``**)**``**;<br />**``** **``**cnt**``**++**``**;<br />**``** **``**} **``**else **``**{**** **``**try **``**{**** wait()**``**;<br />**``** **``**} **``**catch **``**(InterruptedException e) {**** e.printStackTrace()**``**;<br />**``** **``**}**** }**** }**<br />`** **public synchronized void **consumerProduct**() {<br /> notify()**;<br />** if **(**cnt **> **0**) {**`<br />`** System.**out**.println(**“**线程**“ **+ Thread.**currentThread**().getName() + **“**消费第**“ **+ **cnt **+ **“**个产品**“**)**;** **cnt**--**;** **} **else **{<br /> **try **{<br /> wait()**;<br />** **} **catch **(InterruptedException e) {**`<br />`** e.printStackTrace()**;** **}<br /> }<br /> }<br />}`
仓库测试类
**public class **``**StoreHouseTest {**<br />`** **public static void **main**(String[] args) {<br />``<br /> **// **创建仓库类的对象** **StoreHouse storeHouse = **new **StoreHouse()**;<br />** **// **创建线程类对象并启动** **ProduceThread t1 = **new **ProduceThread(storeHouse)**;<br />** **ConsumerThread t2 = **new **ConsumerThread(storeHouse)**;** **t1.start()**;<br />** **t2.start()**;** **}<br />}`
执行结果

