I learned the thread chapter and wrote a producer and consumer question myself.
It simulates the production and consumption of computers.
Java code
Package thread;
Class Computer {
Private int id;
Computer (int id ){
This. id = id;
}
// Override the method toString () from Object
Public String toString (){
Return "Computer: [" + id + "]";
}
}
Class Factory {
Private int items = 0;
Computer [] computer;
Factory (){
Computer = new Computer [6];
}
Public synchronized void push (Computer comp ){
While (items = computer. length ){
Try {
This. wait ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
This. Policy ();
Computer [items ++] = comp;
// Items ++;
}
Public synchronized Computer pop (){
While (items = 0 ){
Try {
This. wait ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
This. Policy ();
Return computer [-- items];
}
}
Class Ibm implements Runnable {
Factory fac = null;
Ibm (Factory f ){
This. fac = f;
}
Public void run (){
For (int I = 0; I <20; I ++ ){
Computer com = new Computer (I );
Fac. push (com );
System. out. println ("IBM assemble one computer" + com );
Try {
Thread. sleep (long) (Math. random () * 100 ));
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}
Class Kisters implements Runnable {
Factory fac = null;
Kisters (Factory f ){
This. fac = f;
}
Public void run (){
For (int I = 0; I <20; I ++ ){
Computer com = fac. pop ();
System. out. println ("Kisters consume one computer" + com );
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
}
Public class ProducerConsumer {
Public static void main (String [] args ){
Factory fac = new Factory ();
Ibm IBM = new Ibm (fac );
Kisters kis = new Kisters (fac );
Thread t1 = new Thread (ibm );
Thread t2 = new Thread (kis );
T1.start ();
T2.start ();
}
}
Author: "16 states of Yanyun"