添加 取出数据方法:
package java基础.Test718;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
public class WaitNotify {
private Queue<Integer> queue;
private int capacity;
public WaitNotify(int capacity) {
this.queue = new LinkedList<>();
this.capacity = capacity;
}
public synchronized void enqueue(Integer item) throws InterruptedException {
while (queue.size()==capacity){
System.out.println("插入数据阻塞队列满了");
wait();
}
queue.add(item);
System.out.println("插入成功"+item);
notifyAll();
}
public synchronized Integer dequeue() throws InterruptedException {
while (queue.isEmpty()){
System.out.println("取数据阻塞队列满了");
wait ();
}
Integer item = queue.poll();
System.out.println("成功取到数据"+item);
notifyAll();
return item;
}
}
这两个方法其实很简单,就是先定一个队列和一个整型数据 capacity(用于存储队列的长度),然后等待通知机制,分别写两个加锁的方法一个添加,一个取出,如果调用添加方法的线程获取到锁,会先判断当前阻塞队列是否满了,满了就进入等待队列,等待被唤醒,如果不满,就添加数据然后唤醒所有出于等待队列的线程(使那些因为队列为空无法取得数据而进入等待状态的线程能够从新加入争夺锁的状态),同理取出方法也一样,只不过他的判断语句是判断是否为空.
测试代码:
package java基础.Test718;
public class Test {
public static void main(String[] args) {
WaitNotify waitNotify = new WaitNotify(5);
Thread thread1 = new Thread(()->{
try {
for (int i=0;i<10;i++){
waitNotify.enqueue(i);
System.out.println("线程1添加"+i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(()->{
try {
for (int i=0;i<10;i++){
waitNotify.enqueue(i);
System.out.println("线程2添加"+i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread3 = new Thread(()->{
try {
for (int i=0;i<10;i++){
int x = waitNotify.dequeue();
System.out.println("线程3取出"+x);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread4 = new Thread(()->{
try {
for (int i=0;i<10;i++){
int x = waitNotify.dequeue();
System.out.println("线程4取出"+x);
Thread.sleep(900);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行完毕");
}
}