Producer and consumer issues (java)

Source: Internet
Author: User

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"
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.