Producer Consumer thread synchronization

Source: Internet
Author: User

A simple introduction to producer and consumer models:

The producer thread produces the item and then places the item in an empty buffer for consumption by the consumer thread. The consumer thread obtains the item from the buffer and then releases the buffer. When a producer thread produces an item, if no empty buffers are available, the producer thread must wait for the consumer thread to release an empty buffer. When consumer threads consume items, if there is no full buffer, then the consumer thread will be blocked until the new

public class Produceconsumer {public static void main (string[] args) {syncstack ss = new Syncstack (); Producer Pro = new Producer (ss); Consumer con = new Consumer (ss); new Thread (PRO). Start (); new Thread (Con). Start ();}} Class Product{int id;public Product (int id) {this.id = ID;} Public String toString () {return "Product:" +id;}} Class Syncstack{int index = 0; product[] Arrpro = new Product[6];p ublic synchronized void push (Product p) {while (index = = arrpro.length) {try {this.wait () ;} catch (Interruptedexception e) {e.printstacktrace ();}} This.notify (); Arrpro[index] = p;index++;} Public synchronized Product POPs () {while (index = = 0) {try {this.wait ();} catch (Interruptedexception e) {E.printstacktrace ();}} This.notify (); Index--;return arrpro[index];}} Class Producer implements Runnable{syncstack SS = Null;public Producer (syncstack ss) {THIS.SS = SS;} public void Run () {for (int i=0; i<20; i++) {Product p = new Product (i); Ss.push (P); System.out.println ("produced:" +p); try {thread.sleep);} catch (InterruptedexceptIon e) {e.printstacktrace ();}}}} Class Consumer implements Runnable{syncstack SS = Null;public Consumer (syncstack ss) {THIS.SS = SS;} public void Run () {for (int i=0; i<20; i++) {Product p = ss.pop (); System.out.println ("Consumed:" +p), try {thread.sleep (+);} catch (Interruptedexception e) {e.printstacktrace ();}}}}

  

The goods were produced.

Producer Consumer thread synchronization

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.