同步锁:生产者-消费者问题

来源:互联网 发布:淘宝apass会员 编辑:程序博客网 时间:2024/05/29 06:53

同步锁:生产者-消费者问题

/** 同步锁:多个线程共同操作一个数据结构中的数据*/public class ProducerConsumer {public static void main(String[] args) {/** 消息队列*/final MessageQueue mq = new MessageQueue(10);/** 创建三个生产者*/for(int p=0;p<3;p++){new Thread(new Runnable(){@Overridepublic void run() {while(true){mq.put("消息来了!");/** 生产消息后,休息100毫秒*/try{Thread.currentThread().sleep(100);}catch(InterruptedException e){e.printStackTrace();}}}},"Producer" + p).start();}/** 创建三个消费者*/for(int s=0;s<3;s++){new Thread(new Runnable(){@Overridepublic void run(){mq.get();/** 消费消息后,休息100毫秒*/try{Thread.currentThread().sleep(100);}catch(InterruptedException e){e.printStackTrace();}}},"Consumer" + s).start();}}/** 建立消息队列*/private static class MessageQueue{/** 放置消息的数据结构*/private String[] messages;/** 将要操作的位置索引*/private int opIndex;public MessageQueue(int size){if(size <= 0){throw new IllegalArgumentException("消息队列的长度至少为1");}messages = new String[size];opIndex = 0;}public synchronized void put(String message){ while(opIndex == messages.length){/** 消息队列已满,生产者等待*/try {wait();} catch (InterruptedException e) {e.printStackTrace();}}messages[opIndex] = message;opIndex++;System.out.println("生产者 " + Thread.currentThread().getName() + " 生产了一条消息: " + message);/** 生产后,对消费者进行唤醒*/notifyAll();}public synchronized String get(){while(opIndex == 0){try{wait();}catch(InterruptedException e){e.printStackTrace();}}String message = messages[opIndex-1];opIndex--;System.out.println("消费者 " + Thread.currentThread().getName() + " 消费了一条消息: " + message);/** 消费后,对生产者进行唤醒*/notifyAll();return message;}}}


0 0
原创粉丝点击