public class ProduceConsume {
public static void main ( String[ ] args) {
SyncStack ss = new SyncStack ( ) ;
Produce p = new Produce ( ss) ;
Consume c = new Consume ( ss) ;
Thread tp = new Thread ( p) ;
Thread tc = new Thread ( c) ;
tp. start ( ) ;
tc. start ( ) ;
}
}
class SteamBread {
int id;
SteamBread ( int id) {
this . id = id;
}
public String toString ( ) {
return "SteamBread:" + id;
}
}
class SyncStack {
int index = 0 ;
SteamBread [ ] stb = new SteamBread [ 6 ] ;
public synchronized void push ( SteamBread sb) {
while ( index == stb. length) {
try {
this . wait ( ) ;
System. out. println ( "--馒头框已经满了...请稍后再生产--" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
this . notify ( ) ;
stb[ index] = sb;
this . index ++ ;
}
public synchronized SteamBread pop ( ) {
while ( index == 0 ) {
try {
this . wait ( ) ;
System. out. println ( "--馒头框已经空了...请稍后再取--" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
this . notify ( ) ;
this . index -- ;
return stb[ index] ;
}
}
class Consume implements Runnable {
SyncStack ss = null;
Consume ( SyncStack ss) {
this . ss = ss;
}
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
SteamBread sb = ss. pop ( ) ;
System. out. println ( "消费了:" + sb) ;
try {
Thread. sleep ( 100 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
}
class Produce implements Runnable {
SyncStack ss = null;
Produce ( SyncStack ss) {
this . ss = ss;
}
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
SteamBread sb = new SteamBread ( i) ;
ss. push ( sb) ;
System. out. println ( "生产了:" + sb) ;
try {
Thread. sleep ( 100 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
}