Java多线程解决

例子:

package com.alipay.sofa.web.test.base;

public class ChickenPCTest {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();

        Provider provider = new Provider(buffer);
        new Thread(provider).start();

        new Consumer(buffer).start();
    }
}

//生产者
class Provider implements Runnable{
    Buffer buffer;

    public Provider(Buffer buffer) {
        this.buffer = buffer;
    }

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

//消费者
class Consumer extends Thread{
    Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run(){
        for (int i = 0; i < 100; i++) {
            try {
                System.out.println("消费了第" + buffer.pop().id +"只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//产品
class Chicken {
    //给每个产品设置一个编号
    public int id;

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

//缓冲区
class Buffer {
    //需要一个产品类型的数组容器 -- 放产品
    Chicken[] container = new Chicken[10];
    int count = 0; //一个容器计数器

    //生产者放入
    public synchronized void push(Chicken chicken){
        //如果满了就不放了
        if (count == container.length){
            try {
                //满了,等待消费消费
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //没满就放入
        container[count] = chicken;
        count++;

        //通知消费者消费了
        this.notify();
    }

    //消费者取出
    public synchronized Chicken pop() throws InterruptedException {
        //如果没有产品就不消费
        if (count == 0){
            //空了,等待生产者生产
            this.wait();
        }
        count --;
        //把具体消费的产品返回
        Chicken chicken = container[count];

        //吃完了,等待生产者生产
        this.notifyAll();
        return chicken;
    }
}

 

posted @ 2020-08-31 19:43  物联网女强人  阅读(153)  评论(0编辑  收藏  举报