注:处于wait状态下的线程没有被唤醒,不能去抢锁
1.容器
public class Stack {
char[] a=new char[5];
int i;
//压入
void pull(char s){
if (i==5) {
return;
}
a[i]=s;
i++;
}
//取出
char push(){
if (i==0) {
return ' ';
}
i--;
return a[i];
}
int size(){
return i;
}
}
2.生产者
public class Producer extends Thread{
private Stack stack;
public Producer(Stack stack) {
this.stack=stack;
}
@Override
public void run() {
while (true) {
synchronized (stack) {
while (stack.size()==5) {
System.out.println("盘子满了,需等待");
try {
stack.wait();
} catch (InterruptedException e) {
System.out.println("盘子满了,需等待");
}
}
char a = (char) ('a'+new Random().nextInt(26));
stack.pull(a);
System.out.println("压入数据 : "+a);
//压入数据后发出通知,盘子里面有数据了
stack.notifyAll();
}
}
}
}
3.消费者
public class Consumer extends Thread {
private Stack stack;
public Consumer(Stack stack) {
this.stack=stack;
}
@Override
public void run() {
while (true) {
synchronized (stack) {
while (stack.size()==0){
System.out.println("盘子里面没有数据,需等待");
try {
stack.wait();
} catch (InterruptedException e) {
System.out.println("盘子里面没有数据,需等待");
}
}
char a = stack.push();
System.out.println("取出数据 : "+a);
//取出数据后发出通知,盘子里面可以放东西了
stack.notifyAll();
}
}
}
}
4.测试
public class Test {
public static void main(String[] args) {
Stack stack = new Stack();
Producer producer = new Producer(stack);
Consumer consumer = new Consumer(stack);
producer.start();
consumer.start();
}
}