public class TestPC {
public static void main ( String [ ] args) {
SynContainer synContainer = new SynContainer ( ) ;
Productor productor = new Productor ( synContainer) ;
Consumer consumer = new Consumer ( synContainer) ;
productor. setPriority ( 10 ) ;
consumer. setPriority ( 1 ) ;
productor. start ( ) ;
consumer. start ( ) ;
}
}
class Productor extends Thread {
SynContainer synContainer;
Productor ( SynContainer synContainer) {
this . synContainer= synContainer;
}
@Override
public void run ( ) {
for ( int i = 1 ; i <= 20 ; i++ ) {
synContainer. push ( new Goods ( i) ) ;
System . out. println ( "生产了第" + i+ "鸡" ) ;
}
}
}
class Consumer extends Thread {
SynContainer synContainer;
Consumer ( SynContainer synContainer) {
this . synContainer= synContainer;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
System . out. println ( "消费了第" + synContainer. pop ( ) . id+ "鸡" ) ;
}
}
}
class Goods {
int id;
public Goods ( int id) {
this . id = id;
}
public Goods ( ) {
}
}
class SynContainer {
Goods [ ] goods = new Goods [ 5 ] ;
int size = 0 ;
public synchronized void push ( Goods good) {
if ( size == goods. length) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
goods[ size++ ] = good;
this . notify ( ) ;
}
public synchronized Goods pop ( ) {
if ( size == 0 )
{
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
size-- ;
Goods good= goods[ size] ;
this . notify ( ) ;
return good;
}
}