生产者消费者
来源:互联网 发布:淘宝客推广中pid是什么 编辑:程序博客网 时间:2024/05/21 17:51
package org.tuyifei.dao;import java.util.LinkedList;public class Container {private static final LinkedList<String> disk = new LinkedList<>();private static byte[] b = new byte[0];private static int max = 10;Object o = new Object();public void put(String food) {if(disk.size()<=max){System.out.println("生产者生产:"+food);synchronized (disk) {//因为LinkList线程不安全,就是添加了可能size也变了但是没存储进去disk.add(food);try {synchronized (b) {//唤醒所有消费者,如果要加队列上线,再重新建个锁挂到上面,等待消费者唤醒b.notifyAll();}} catch (Exception e) {e.printStackTrace();}}}}public void eat(){if(disk.size()!=0){System.out.println("消费者吃了"+disk.getLast());synchronized (disk) {disk.removeLast();}}else{synchronized (b) {try {//如果没资源消费者等待b.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}}
package org.tuyifei.dao;import java.util.Random;public class Test01 {public static void main(String[] args) {new Thread(new Cooker()).start();new Thread(new Customer()).start();new Thread(new Customer()).start();new Thread(new Customer()).start();new Thread(new Customer()).start();new Thread(new Customer()).start();new Thread(new Customer()).start();new Thread(new Customer()).start();}}class Cooker implements Runnable{private static final String[] food = {"砒霜","农药","吸铁石","炸药","水泥"};public static void make(){//创建一个随机食物new Container().put(food[new Random().nextInt(food.length)]);}@Overridepublic void run() {while (true) {make();}}}class Customer implements Runnable{@Overridepublic void run() {while (true) {new Container().eat();}}}我学多线程的一个总结:1.要保证这个类的当前对象同步,就用this或者当前对象的成员变量当锁,要保证这个类的所有对象都同步,就用一个静态变量,2.要让一个对象进入wait()状态,要把它挂到一个钩子上去,这个钩子就是锁对象(任意锁对象都可以,选择是单例还是多例参考第一条),然后再用这个锁对象的notify()方法唤醒上面的等待对象
0 0
- 生产者/消费者
- 生产者/消费者
- 生产者消费者
- 生产者-消费者
- 生产者消费者
- 生产者 消费者
- 生产者-消费者
- 生产者 消费者
- 生产者、消费者
- 生产者/消费者
- 生产者消费者
- 生产者/消费者
- 生产者消费者
- 生产者消费者
- 生产者消费者
- 生产者消费者
- 生产者消费者
- 生产者、消费者
- 02分治算法-01二分查找
- 快速排序 Java
- OkHttp:Java 平台上的新一代 HTTP 客户端
- 【c++】new
- struts 接收参数(通过model接收)
- 生产者消费者
- 发布Qt5程序时图标的设置
- mac系统启动startup.sh tomcat启动失败问题!
- BZOJ3143: [Hnoi2013]游走
- [Leetcode] String to Integer (atoi)
- gcc编译器 工程管理器
- MyEclipse 快捷键
- [BZOJ3997][TJOI2016]组合数学 平面图
- PHP底层的运行机制与原理