使用 wait notify 实现一个队列,队列有2个方法,add 和 get 。add方法往队列中添加元素,get方法往队列中获得元素。队列必须是线程安全的。如果get执行时,队列为空,线程必须阻塞等待,直到有队列有数据。如果add时,队列已经满,则add线程要等待,直到队列有空闲空间。使他工作在多线程的环境下,证明,它的工作是正确的。给出程序和运行的截图。
//关键点: wait() notify() 锁住同一资源
private static final int maxLenth = 10;
static Object lock = new Object();
private Queue<Integer> list = new LinkedList<Integer>();
private Integer i = 0;
public void add() throws Exception{
synchronized (lock) {
Thread.sleep(1000);
if(list.size()==maxLenth){
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println("队列满了当前list长度:"+list.size());
lock.notifyAll();
}
}
list.add(++i);
System.out.println("加入i值:"+i);
lock.notifyAll();
}
}
public Integer get() throws Exception{
synchronized (lock) {
Thread.sleep(1000);
if(list.size()==0){
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println("队列空了当前list长度:"+list.size());
lock.notifyAll();
}
return null;
}
Integer poll = list.poll();
System.out.println("移除i值:"+poll);
lock.notifyAll();
return poll;
}
}
public static void main(String[] args) throws Exception {
Task2 t = new Task2();
for (int i = 0; i < 5; i++) {
new Thread(){
public void run() {
while(true){
try {
t.add();
} catch (Exception e) {
e.printStackTrace();
}
}
};
}.start();
}
for (int i = 0; i < 5; i++) {
new Thread(){
public void run() {
while(true){
try {
t.get();
} catch (Exception e) {
e.printStackTrace();
}
}
};
}.start();
}
}