生产者消费者

来源:互联网 发布:淘宝客推广中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
原创粉丝点击