java wait()和notify()(生产者和消费者问题)
程序员文章站
2022-07-12 19:33:24
...
转载请注明出处:http://shuiguaiqq.iteye.com/blog/2065452
以前一直都是看看,似懂非懂,今天就手写了下,加深理解。
整个问题(是一个多线程同步问题的经典案例)简单来说就是说有一个仓库,里面有很多产品,生产者负责往里塞产品,但产品到达8个时不能再往里塞,等到小于8个时再继续,消费者负责往外拿产品,只要仓库里有产品就一直拿直到仓库产品一个都没就停下,等到有产品再继续。
好了,话糙理不糙,看代码:
import java.util.ArrayList; import java.util.List; import java.util.Random; public class Test { public static void main(String[] args) { Stoarge stoarge = new Stoarge(); new Thread(new Producer(stoarge)).start(); new Thread(new Producer(stoarge)).start(); new Thread(new Customer(stoarge)).start(); } } class Product { private int code; public Product(int code) { this.code = code; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } @Override public String toString() { return "Pdt(" + code + ")"; } } class Producer implements Runnable { private Stoarge stoarge; public Producer(Stoarge stoarge) { this.stoarge = stoarge; } @Override public void run() { while (true) { stoarge.proOne(); } } } class Customer implements Runnable { private Stoarge stoarge; public Customer(Stoarge stoarge) { this.stoarge = stoarge; } @Override public void run() { while (true) { stoarge.cusOne(); } } } class Stoarge { static final int MAX_NUMBER = 8; static Random random = new Random(); private List<Product> products = new ArrayList<Product>(); public List<Product> getProducts() { return products; } public void setProducts(List<Product> products) { this.products = products; } public synchronized Product cusOne() { while (products.size() <= 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Product p = products.get(products.size() - 1); products.remove(products.size() - 1); notify(); System.out.print(" Stoarge All("+products.size()+"):"); display(); System.out.println("------------此次消费:" + p); return p; } public synchronized void proOne() { while (products.size() >= Stoarge.MAX_NUMBER) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Product p = new Product(Stoarge.random.nextInt(20) + 1); products.add(p); notify(); System.out.print(" Stoarge All("+products.size()+"):"); display(); System.out.println("------------此次生产:" + p); } private void display() { String str = ""; for (Product p : products) { str += p.toString() + "_"; } if (products.size() > 0) { System.out.print(str.substring(0, str.length() - 1)); } } }
上一篇: adventnet trap
下一篇: Shell调试技术总结
推荐阅读
-
Java多线程-同步:synchronized 和线程通信:生产者消费者模式
-
关于Object类中的wait()和notify()方法实现生产者和消费者模式
-
Java多线程之wait和notify
-
java多线程协作object.notify和object.wait
-
wait和notify实现生产者消费者模型
-
java wait()和notify()(生产者和消费者问题)
-
如何在 Java 中正确使用 wait, notify 和 notifyAll – 以生产者消费者模型为例
-
java 多线程中的 wait 和 notify
-
java 多线程中的 wait 和 notify
-
经典问题-生产者和消费者问题