Thread synchronization – Examples of producers and consumers

Source: Internet
Author: User
Tags mutex sleep
Preface

Small series recently in the learning thread of the content, found that the small examples of the implementation of the very interesting, of course, is also very useful, the content of the thread, almost every day we will encounter, but not special attention, the following small tape everyone to further understand the thread bar.
Threads and Processes 1. A thread is a sequential control flow within a program
2. Thread and Process differences:
(1) Each process has a separate code and data space (process context), the switching between processes will have a large overhead;
(2) thread can be considered as a lightweight process, sharing code and data space with a class of threads, each thread has a separate running stack and program counter (PC), thread switching overhead is small;
(3) Multi-process: can run multiple tasks (programs) simultaneously in the operating system;
(4) Multithreading: Multiple sequential streams in the same application are executed concurrently.

Thread Synchronization

In the Java language, the concept of object mutexes is introduced to ensure the integrity of shared data operations.
1. Object Mutex Lock
Each object corresponds to a tag that can be called a "mutex", which guarantees that only one thread can access the object at any one time.
2. Keyword synchronized
Synchronized to associate with an object's mutex, when an object is decorated with synchronized, indicating that the object can only be accessed by one thread at any one time.
examples of producers and consumers
1. Code Analysis
(1) A total of 5 classes: Main Program class Producerconsumer, production of food class Wotou, implement thread synchronization lock class Syncstack, producer class producer and consumer class consumer
(2) Producer and consumer realize the interface runnable, belong to two threads;
(3) When performing thread synchronization, if the number of productions exceeds the index value 6 of the container, then the Object.wait () method is executed, otherwise another thread is activated to consume consumer, using the object. Notify () method.
2. Code implementation

public class Producerconsumer {public static void main (string[] args) throws exception{Syncstack ss=new Sy
        Ncstack ();
        Producer p=new Producer (ss);

        Consumer c=new Consumer (ss);
        New Thread (P). Start ();


    New Thread (c). Start ();
    }} class wotou{int id;
    Wotou (int id) {this.id=id;
    The public String toString () {return "Wotou:" +ID;
    }} class syncstack{int index=0;

    Wotou[] Arrwt=new wotou[6];
            Public synchronized void push (Wotou wt) {while (index==arrwt.length) {try{this.wait ();
            }catch (interruptedexception e) {e.printstacktrace ();
        }} this.notify ();
        ARRWT[INDEX]=WT;
    index++;
            Public synchronized Wotou POPs () {while (index==0) {try{this.wait ();
            }catch (interruptedexception e) {e.printstacktrace ();
      }  } this.notify ();
        index--;

    return Arrwt[index];
    }} class Producer implements runnable{Syncstack ss=new syncstack ();
    Producer (Syncstack ss) {This.ss=ss;
            public void Run () {for (int i=0;i<=20;i++) {Wotou wt=new Wotou (i);
            Ss.push (WT);
            System.out.println ("produced" +WT);
            try{thread.sleep ((int) (Math.random () *1000));
            }catch (interruptedexception e) {e.printstacktrace ();
    }}}} class Consumer implements runnable{Syncstack ss=new syncstack ();
    Consumer (Syncstack ss) {This.ss=ss;
            public void Run () {for (int i=0;i<=20;i++) {Wotou wt=ss.pop ();
            System.out.println ("consumed" +wt);
            try{thread.sleep ((int) (Math.random () *1000));
            }catch (interruptedexception e) {e.printstacktrace (); }
        }
    }
}
Summary

Thread synchronization is a frequently asked question in an interview, and this small example can be helpful if you can write it out and fully understand it.
Thank you for your visit.

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.