java 并发编程(四)之临界区中使用条件

来源:互联网 发布:淘宝卖茶叶要怎么办理 编辑:程序博客网 时间:2024/06/06 02:02


我们可以使用synchronized机制实现线程同步,通过保证“临界区”的访问顺序来保证共享资源状态的正确性。

然而,更多情况是我们不仅需要获得对“临界区”的访问,在获得访问权限后也要判断更多的条件来确定是否

要做出后续的操作。

典型的问题就是“生产者-消费者”问题,当生产者A获得对缓存的访问后,还要判断目前缓存是否可以生产,

否则的话就要让出时间片,等待合适的实际。

我们通过代码来进行举例:

我们定义四个类:

1、EventStorage 作为存储缓冲区;

2、Producer 生产者;

3、Consumer 消费者;

4、Test 测试类;


package com.z.linjiequshiyongtiaojian_3;import java.util.Date;import java.util.LinkedList;import java.util.concurrent.TimeUnit;public class EventStorage {private int maxSize;private final LinkedList<Date> storage;private int size;private int line = 1;public EventStorage(){maxSize = 10;this.storage = new LinkedList<Date>();}public synchronized void set() throws InterruptedException{while(storage.size() >= maxSize){wait();}TimeUnit.MILLISECONDS.sleep(100);Date date = new Date();storage.add(date);System.out.println(line++ +":" +"插入的数值:" + date + "___" + "当前存储大小:"+ ++this.size);this.notifyAll();}public synchronized void get() throws InterruptedException{while(storage.size() <= 0){wait();}TimeUnit.MILLISECONDS.sleep(100);System.out.println(line++ +":" +"取出的数值:"+storage.poll()+"___" +"当前存储大小:" + --this.size);this.notifyAll();}public int size(){return this.size;}}


package com.z.linjiequshiyongtiaojian_3;public class Producer implements Runnable{private final EventStorage eventStorage;public Producer(EventStorage eventStorage){this.eventStorage = eventStorage;}public void run(){for(int i = 0; i < 100; i ++){try {eventStorage.set();} catch (InterruptedException e) {System.err.println(e);}}}}

package com.z.linjiequshiyongtiaojian_3;public class Consumer implements Runnable{private final EventStorage eventStorage;public Consumer(EventStorage eventStorage){this.eventStorage = eventStorage;}public void run(){for(int i = 0; i < 100; i ++){try{eventStorage.get();}catch(InterruptedException e){System.err.println(e);}}}}

package com.z.linjiequshiyongtiaojian_3;public class Test {public static void main(String[] args) throws InterruptedException{EventStorage eventStorage = new EventStorage();Thread producer = new Thread(new Producer(eventStorage));Thread consumer = new Thread(new Consumer(eventStorage));producer.start();consumer.start();producer.join();consumer.join();System.out.println("存储的最终大小是:" + eventStorage.size());}}

当生产消息时,如果当前缓冲区的大小超出了上界,那么就wait让出时间片,理想情况下是某个消费者获得时间片在取出数据更新缓存大小状态后生产者重新生产。

另外对于wait notify notify的说明参考:点击打开链接


0 0