package producer_consumer;
/*管程法
生产者
消费者
生产消费的对象
缓冲区
*/
public class MonitorMethodTest { //管程法
public static void main(String[] args) {
//24.创建缓冲区,并填入生产者和消费者存储所需要的缓冲区
BufferZoneTest bufferZoneTest = new BufferZoneTest();
//25.创建生产者
new ProducerTest(bufferZoneTest).start();
//26.创建消费者
new ConsumerTest(bufferZoneTest).start();
}
}
//——————CLASS——————————————
class ProducerTest extends Thread { //生产者
//16.定义一个缓冲区变量
BufferZoneTest bufferZoneTest;
//17.定义缓冲区变量的构造方法
public ProducerTest(BufferZoneTest bufferZoneTest) {
this.bufferZoneTest = bufferZoneTest;
}
//18.重写run方法
@Override
public void run() {
//19.循环输出
for (int i = 0; i < 100; i++) {
System.out.println("生产者 = " + i);
//20.将创建的对象存入构造方法中的缓冲区,即为——生产者!
bufferZoneTest.BZTInPutTest(new InteractionTest(i));
}
}
}
//——————CLASS——————————————
class ConsumerTest extends Thread { //消费者
//21.与生产者同理,定义一个缓冲区变量
BufferZoneTest bufferZoneTest;
//22.编写缓冲区变量的构造方法
public ConsumerTest(BufferZoneTest bufferZoneTest) {
this.bufferZoneTest = bufferZoneTest;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//23.将构造方法中缓冲区的对象取出,即为——消费者!
System.out.println("消费者 = " + bufferZoneTest.BZTOutPutTest().id); //此处"bufferZoneTest.BZTOutPutTest().id"因为不需要对象只需要对象中的存储的数据所以使用".id"
}
}
}
//——————CLASS——————————————
class InteractionTest { //生产者消费者交互对象
int id;
public InteractionTest(int id) {
this.id = id;
}
}
//——————CLASS——————————————
class BufferZoneTest { //交互对象的数据缓冲区
//1.定义交互对象缓冲区的个数,相当于一个仓库
InteractionTest[] interactionTests = new InteractionTest[10]; //交互
//2.定义一个指示缓冲区存储中下次存储位置的标记
int pointer = 0; //指针
//3.创建生产者输入的存储方法
public synchronized void BZTInPutTest(InteractionTest interactionTest){
//4.判断仓库是否存满,即判断缓冲区存储位置标记与仓库的长度
if (pointer == interactionTests.length) {
//5.当仓库存满则停止生产者进行生产,即停止当前线程
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//6.将生产者生产的对象存储在缓冲区仓库中
interactionTests[pointer] = interactionTest;
//7.对存储位置标记进行增加,即下次存储的位置
pointer++;
//8.在生产者生产的过程中可能会存在等待的线程,需将这些线程唤醒
this.notifyAll();
}
//——————Method——————————————
//9.创建一个为消费者输出的方法,返回的类型即为交互的对象
public synchronized InteractionTest BZTOutPutTest() {
//10.判断仓库中是否还有库存,即判断缓冲区存储位置标记是否等于0
if (pointer == 0) {
//11.当仓库中没有库存时,则停止消费者线程
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//12.对存储位置标记进行减少,即上次存储的位置
pointer--;
//13.对上次存储的对象进行存储
InteractionTest interactionTest = interactionTests[pointer];
//14.在消费者消费仓库库存的过程中,生产者可能会因仓库存满进行等待,将他唤醒
this.notifyAll();
//15.将得到的数据返回
return interactionTest;
}
}
【程序】管程法
最新推荐文章于 2022-02-21 17:38:11 发布