java linkedlist wait_使用Notify 和 wait ,使用Linklist实现生产者消费者问题

注释很清楚的,

import java.util.LinkedList;

import java.util.Queue;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

//产品

class Product

{

String name=null;

public Product(String name)

{

this.name=name;

}

}

class Buffer

{

private Queue queue=new LinkedList();//一个普通队列,同时作为同步的对象

private final int size=5; //最大长度为,可以自己调整

public void add(Product p)//

{

synchronized (queue) {

while(queue.size()==size)

{

System.out.println(Thread.currentThread().getName()+"队列已经满了,生产者释放锁");

try {

queue.wait(); //队列未满,则放弃锁,进行挂起,等到queue,notify,有个线程会重新从wait后运行

} catch (Interrup

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
生产者和消费者问题是一个经典的并发编程问题,可以使用Java语言来模拟实现。下面是一个使用Java多线程实现生产者和消费者问题的示例代码: ```java import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { public static void main(String[] args) { Queue<Integer> queue = new LinkedList<>(); int maxSize = 10; Thread producerThread = new Thread(new Producer(queue, maxSize), "Producer"); Thread consumerThread = new Thread(new Consumer(queue), "Consumer"); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { private Queue<Integer> queue; private int maxSize; public Producer(Queue<Integer> queue, int maxSize) { this.queue = queue; this.maxSize = maxSize; } @Override public void run() { while (true) { synchronized (queue) { while (queue.size() == maxSize) { try { System.out.println("Queue is full, waiting for consumer to consume..."); queue.wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } int number = (int) (Math.random() * 100); queue.add(number); System.out.println("Produced " + number); queue.notifyAll(); } } } } static class Consumer implements Runnable { private Queue<Integer> queue; public Consumer(Queue<Integer> queue) { this.queue = queue; } @Override public void run() { while (true) { synchronized (queue) { while (queue.isEmpty()) { try { System.out.println("Queue is empty, waiting for producer to produce..."); queue.wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } int number = queue.remove(); System.out.println("Consumed " + number); queue.notifyAll(); } } } } } ``` 上面的代码中,生产者线程和消费者线程都是使用`Runnable`接口实现的,并且都使用`synchronized`关键字来保证线程安全。生产者线程在队列满时等待,消费者线程在队列空时等待,当有新的元素加入队列时,生产者线程会唤醒等待的消费者线程,当有元素被消费时,消费者线程会唤醒等待的生产者线程。这种实现方式可以有效避免死锁和饥饿等并发编程问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值