java多线程-synchronized实现生产者消费者

生产者类

import java.util.Queue;

//生产者
public class Producer implements Runnable{
    private Queue<String> mylist;
    private int maxLen;


    public Producer(Queue<String> mylist , int maxLen){
        this.mylist = mylist;
        this.maxLen = maxLen;

    }

    @Override
    public void run() {
        int cursize = 0;
        while (true){
            cursize ++;
            synchronized (mylist){
                if(mylist.size() == maxLen){
                    System.out.println(" 满了");
                    try {
                        mylist.wait(); //等待 阻塞当前线程并释放锁
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产者生产 book" + cursize);
                mylist.add("book" + cursize); //生产
                mylist.notify(); // 提示消费者消费
            }
        }


    }
}

消费者类

import java.util.Queue;

public class Consumer implements Runnable{
    Queue<String> mylist;
    int maxLen;

    public Consumer(Queue<String> mylist , int maxLen){
        this.mylist = mylist;
        this.maxLen = maxLen;

    }
    @Override
    public void run() {
        while (true){
            synchronized (mylist){
                if(mylist.isEmpty()){
                    System.out.println(" 空了");
                    try {
                        mylist.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                String book = mylist.remove();
                System.out.println("消费者消费" + book);
                mylist.notify();
            }

        }
    }
}

运行

public class ProducerConsumerTest {
    public static void main(String[] args) throws InterruptedException {
        Queue<String> mylist = new LinkedList<>();
        Producer producer = new Producer(mylist,10);
        Consumer consumer = new Consumer(mylist,10);
        new Thread(producer).start();
        Thread.sleep(1000);
        new Thread(consumer).start();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值