其他分享
首页 > 其他分享> > 管程法实现线程通信

管程法实现线程通信

作者:互联网

管程法实现线程通信

例子:

生产者只负责生产鸡

消费者只负责消费鸡

缓冲区负责存放鸡,有存入方法,缓冲区满了等待消费者消费,没有满生产者生产,通知消费者消费

缓冲区有弹出方法,缓冲区为空等待生产者生产,不为空通知生产者生产

代码

package com.example.multi_thread;

import lombok.SneakyThrows;


// 管程法
public class TestPC {
    public static void main(String[] args) {
        SyncContainer container = new SyncContainer();

        Productor productor = new Productor(container);
        Consumer consumer = new Consumer(container);
        new Thread(productor).start();
        new Thread(consumer).start();

    }
}

// 生产者、消费者、产品、缓冲区

//生产者只负责生产东西
class Productor implements Runnable {
    SyncContainer syncContainer = new SyncContainer();

    public Productor(SyncContainer syncContainer) {
        this.syncContainer = syncContainer;
    }

    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            syncContainer.push(new Chicken(i));
            System.out.println("生产了第" + i + "只鸡");

        }
    }
}

// 消费者
class Consumer implements Runnable {
    SyncContainer syncContainer = new SyncContainer();

    public Consumer(SyncContainer syncContainer) {
        this.syncContainer = syncContainer;
    }

    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            System.out.println("消费了第" + syncContainer.pop().id + "只鸡");

        }
    }
}

// 产品是鸡
class Chicken {
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

// 缓冲区
class SyncContainer {
    Chicken[] chickens = new Chicken[10];

    int count;


    public synchronized void push(Chicken chicken) throws InterruptedException {
        if (count == 10) {
            // 等待消费者消费
            wait();
        }

        // 生产,并通知消费者
        chickens[count] = chicken;
        count++;
        notifyAll();
    }

    public synchronized Chicken pop() throws InterruptedException {
        if (count == 0) {
            // 等待生产
            wait();
        }

        count--;
        Chicken chicken = chickens[count];
        notifyAll();
        return chicken;
    }

}

标签:count,管程,通信,SyncContainer,线程,new,Chicken,syncContainer,public
来源: https://www.cnblogs.com/Oh-mydream/p/15556769.html