简单使用wait()和notify()方法模拟队列Queue
过程描述:.定义一个类队列类MyQueue,有两个方法,添加数据和取数据,此队列类有一个容器,容器有最大值和最小值,有一个计数器,还需要有一个对象锁,保证同步,即在多个线程操作同一对象的方法时需要按照我们的意愿进行操作
package com.neo.study001.redio08;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author liyy
* @date 2020/4/23 21:12
* @Function :使用wait()与notify()模拟队列
* @Tips:
* 1.wait()与notify()必须配合synchronized关键字使用
* 2.wait()会释放锁,notify()不会释放锁
*/
public class MyQueue {
private final LinkedList list = new LinkedList();//容器
private final AtomicInteger count = new AtomicInteger();//计数器
private final int minSize = 0;//最小容量
private final int maxSize;//最大容量,使用构造函数定义
private final Object lock = new Object();//对象锁
public MyQueue(int size) {
this.maxSize = size;
}
public void put(Object obj) {
synchronized (lock) {
if (count.get() == maxSize) {//添加操作达到最大值时,线程处于等待状态
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(obj);
count.incrementAndGet();//计数器++操作
System.out.println(Thread.currentThread().getName()+"添加了一个元素为:"+obj);
lock.notify();//有一个线程已经启动,此时容器为空,添加了一个obj,需要通知等待着调用take()方法的线程
}
}
public Object take() {
Object o = null;
synchronized (lock) {
if (count.get() == minSize) {//获取操作达到最小值0时,线程处于等待状态
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o = list.removeLast();
count.decrementAndGet();//计数器--操作
System.out.println(Thread.currentThread().getName()+"移除了一个元素为:"+o);
lock.notify();//有一个线程已经启动,此时容器满的,取走了一个obj,需要通知等待着调用put()方法的线程
}
return o;
}
public static void main(String[] args) {
final MyQueue myQueue = new MyQueue(5);
myQueue.put("1");
myQueue.put("2");
myQueue.put("3");
myQueue.put("4");
myQueue.put("5");
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
myQueue.put("6");
myQueue.put("7");
}
},"t1");
t1.start();
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
myQueue.take();
myQueue.take();
}
},"t2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}