public class ProducerConsumer {
public static void main(String[] args) {
LZ a = new LZ();
Producer b1 = new Producer(a);
Consumer c = new Consumer(a);
new Thread(c).start();
new Thread(b1).start();
}
}
class MT{
int id = 0;
MT(int id) {
this.id = id;
}
public String toString(){
return "馒头:"+id;
}
}
class LZ{
MT[] arrmt = new MT[6];
int index = 0;
}
class Producer implements Runnable{
LZ z =null;
Producer(LZ l){
z = l;
}
public synchronized void push(LZ z){
for(int i=0; i<20; i++){
while(z.index == z.arrmt.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
MT m= new MT(i);
z.arrmt[z.index] = m;
z.index++;
System.out.println("生产"+m);
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void run(){
push(z);
}
}
class Consumer implements Runnable{
LZ z =null;
Consumer(LZ l){
z = l;
}
public synchronized void pop(LZ z){
for(int i=0; i<20; i++){
while(z.index == 0){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
z.index--;
System.out.println("消费"+z.arrmt[z.index]);
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void run(){
pop(z);
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
消费者启动时
z.index
就是0
,这里自然就让线程进入等待中了。而你的
notify
调用老是对自己进行,这有什么用……能运行这行代码,表示现在就不在等待中,反之,等待中的线程也不会运行这段代码。