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

我们可以使用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 storage;

private int size;

private int line = 1;

public EventStorage(){

maxSize = 10;

this.storage = new LinkedList();

}

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值