package com. z ;
public class Main {
public static void main ( String [ ] args) {
Goods goods = new Goods ( ) ;
new Producer ( goods) . start ( ) ;
new Comsumer ( goods) . start ( ) ;
}
}
package com. z ;
public class Goods {
private String food;
private boolean empty = true ;
public synchronized String getFood ( ) {
while ( empty) {
try {
wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
empty = true ;
notifyAll ( ) ;
return food;
}
public synchronized void setFood ( String food) {
while ( ! empty) {
try {
wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
empty = false ;
this . food = food;
notifyAll ( ) ;
}
}
package com. z ;
public class Producer extends Thread {
private Goods goods;
public Producer ( Goods goods) {
this . goods = goods;
}
@Override
public void run ( ) {
String [ ] pfood = { "汉堡" , "可乐" , "热狗" , "咖啡" , "鸡块" , null } ;
for ( String s : pfood) {
if ( s== null ) break ;
System . out. println ( "生产者正在生产" + s+ Thread . currentThread ( ) ) ;
try {
Thread . sleep ( 2000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
goods. setFood ( s) ;
}
goods. setFood ( null ) ;
}
}
package com. z ;
public class Comsumer extends Thread {
private Goods goods;
public Comsumer ( Goods goods) {
this . goods = goods;
}
@Override
public void run ( ) {
String food= null ;
while ( ( food= goods. getFood ( ) ) != null ) {
System . out. println ( "消费者正在吃" + food+ Thread . currentThread ( ) ) ;
try {
Thread . sleep ( 2000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System . out. println ( "程序退出" ) ;
return ;
}
}