Java multi-Threading and Concurrency (v.) Producer and Consumer case __java

Source: Internet
Author: User
Producer and consumer application cases

Multithreading in the development of a classic case, is the producer-consumers, producers continue to produce products, consumers continue to take away products.
For example: There is a chef and a waiter in the restaurant, the waiter must wait for the cook to prepare the meal. When the chef is ready, he notifies the waiter, then the waiter orders, and then returns to wait. This is an example of task writing, where the chef represents the producer while the waiter represents the consumer.

First we need to create the corresponding class:
Producer class, for the production of products (our products here refer to food, which are shown below)
Suppose we produce two kinds of "Chongqing facet" and "sweet and sour pork fillet",

Producer Class
Producter implements Runnable {

    private Food Food;

    Public Producter (Food Food) {
        this.food = Food;
    }

    @Override public
    Void Run () {
        for (int i = 0; i < i++) {
            if (i% 2 = 0) {
                food.set ("Chongqing facet", "is delicious!") !!");
            } else {
                //is odd when
                food.set ("Sweet and sour Pork fillet", "Sour sweet delicious!");}
    }}


Consumer category, that is, consumption of food

Consumer Classes Class
customer implements Runnable {
    private Food Food;

    Public Customer (Food Food) {
        this.food = Food;
    }

    @Override public
    Void Run () {for
        (int i = 0; i < i++) {
            try {
                thread.sleep (1000);
            } catch (in Terruptedexception e) {
                //TODO auto-generated catch block
                e.printstacktrace ();
            }
            Food.get ();}}

Consumption and production of objects, food classes, this is our core class, synchronized code embodied in this class.

Note: Here I use the wait () method and the Notify () method I mentioned in my previous blog, simply to illustrate:
1. The wait method indicates that the current thread is in the waiting state, will give up the CPU and release the lock on the monitor, but pay attention to the difference with the sleep method, the sleep method will not give up after the execution of the lock, the code in the execution of the wait method will be "Wake up",
2. The Notify method, which wakes up the waiting method and a Notifyall method, differs in that the former awakens only one of them, while the latter wakes all

Objects of consumption (data), food classes class Food {private string name;//menu name private string efficacy;//efficacy//True indicates that you can produce false indicating that you can consume

    Private Boolean flag = true;
    Public String GetName () {return name;
    public void SetName (String name) {this.name = name;
    Public String getefficacy () {return efficacy;
    } public void Setefficacy (String efficacy) {this.efficacy = efficacy;
        Public Food (string name, string efficacy) {super ();
        THIS.name = name;
    This.efficacy = efficacy;
        ///Production products public synchronized void set (string name, string efficacy) {//System.out.println ("Chongqing facet");
                means not producing, but can consume, need to give up the time if (!flag) {try {//wait is different from hibernation, sleep will enter wait but will not make the lock This.wait ()///indicates that the current thread is in the waiting state, yields the CPU and releases the lock on the monitor (Interruptedexception e) {/T Odo auto-generated catch block E.printstacktrace ();

        } this.setname (name);
        try {thread.sleep (1000);
        catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();

        } this.setefficacy (efficacy);
        Flag = False After the production is finished;
                This.notify ()//Wake up other threads on the monitor (just wake up one)} public synchronized void get () {if (flag) {try {
            This.wait (); 
            catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
        } System.out.println (This.getname () + "->" + this.getefficacy ());
        This.notify ();
    Flag = true; Public Food () {}}

Test class

public class ThreadDemo4 {public

    static void Main (string[] args) {
        Food Food = new Food ();
        Producter p = new Producter (food);
        Customer C = new customer (food);

        thread T1 = new Thread (p);
        Thread t2 = new Thread (c);

        T1.start ();
        T2.start ();
    }

Code Execution Results:

The above is purely personal opinion, if there is a shortage of the hope that the expert pointed out, will be grateful, if you like to Exchange learning experience please give me a message thank you.

Original article, reprint please indicate the source

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.