36套java进阶高级架构师视频+38套大数据视频 保证全是硬货需要的
+微信:
du13797566440
package com.bjsxt.base.sync005;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 作者:dlj
* 描述:wait与notify写消息队列
* 时间:2017年12月19日下午6:26:36
*/
public class queue_test {
volatile List<String> list=new ArrayList<>();
private AtomicInteger count=new AtomicInteger(0);//创建一个计数器
private int maxSize=5;//最大消息长度
private int minSize=0;//最小消息长度
private void put(String s){
synchronized (queue_test.class) {
if(count.get()==maxSize){
try {
queue_test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(s);
System.out.println("put------------"+s);
count.incrementAndGet();
queue_test.class.notify();//此处get线程有可能被阻塞,唤醒get线程
}
}
private String get() throws Exception{
synchronized (queue_test.class) {
if(count.get()==minSize){
queue_test.class.wait();
}
String remove = list.remove(0);
count.decrementAndGet();
queue_test.class.notify();
return remove;
}
}
public static void main(String[] args) throws Exception {
queue_test queue_test = new queue_test();
queue_test.put("a");
queue_test.put("b");
queue_test.put("c");
queue_test.put("d");
queue_test.put("e");
new Thread(new Runnable() {
@Override
public void run() {
queue_test.put("f"); //此时当前线程会被阻塞
queue_test.put("g"); //g将永远被阻塞
}
}).start();
Thread.sleep(2000);
new Thread(new Runnable() {
@Override
public void run() {
try {
String string = queue_test.get(); // put线程停止阻塞
System.out.println("get----------"+string);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}