Java multi-thread producer consumer problem <二> : Use reentrant locks, conditional variables to gracefully address producer consumer issues __java

Source: Internet
Author: User

Java5 has added a lot of thread synchronization features, such as explicit lock, read-write lock readwritelock, conditional variable condition, etc., although these features can be implemented using the previous synchronized synchronization keyword, but their use of synchronization keyword not only manages chaos , and error prone. The following is a better solution to the problem of producer consumers by using explicit lock and conditional variable condition, and it is well understood that the readers of lock and condition can consult the relevant instructions themselves.

Consumer.java

Package Creatorandconsumer;

public class Consumer implements Runnable {
    /**
     * Thread Resource * *
    private Plate Plate;

    Public Consumer (Plate Plate) {
        this.plate = Plate;
    }

    @Override public
    Void Run () {
        Plate.getegg ();
    }
}
Creator.java

Package Creatorandconsumer;

/** *
 producer
 * * @author Martin/Public
class Creator implements Runnable {
    /**
     * Thread Resource
     * /
    private Plate Plate;

    Public Creator (Plate Plate) {
        this.plate = Plate;
    }

    @Override public
    Void Run () {
        Object egg = new Object ();
        Plate.addegg (egg);
    }


Plate.java

Package Creatorandconsumer;
Import java.util.List;

Import java.util.concurrent.locks.*; /** * plate, indicating shared resources * * @author Martin/public class Plate {private list<object> eggs = new Arraylist<obj

    Ect> ();

    /** * Lock */private lock lock;

    /** * is greater than 0 pieces of variable, used to ensure that the consumption of resources can be consumed * * Private Condition more0condition;
        Public Plate () {lock = new reentrantlock ();
    More0condition = Lock.newcondition ();
        /** * Get Egg * * @return/public Object Getegg () {lock.lock ();
            try {while (Eggs.size () < 1) {more0condition.await ();
            SYSTEM.OUT.PRINTLN ("Consumers take eggs, current remaining:" + eggs.size ());
            Object egg = eggs.get (0);
            Eggs.remove (0);
        return egg;
        catch (Interruptedexception e) {e.printstacktrace ();
        finally {Lock.unlock ();
    return null;
     }


    /*** Add Egg * * @return/public void Addegg (Object egg) {lock.lock ();
        System.out.println ("producer eggs, current remaining:" + eggs.size ());
        Eggs.add (egg);
        More0condition.signalall ();
    Lock.unlock ();
 }

}

Tester.java
Package Creatorandconsumer;

Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;

public class Tester {public
    static void Main (string[] args)
    {
        //shared resource
        Plate Plate = new Plate ();
        Executorservice pool = executors.newfixedthreadpool (MB);

        Add producer and consumer for
        (int i = 0; i < 1000 i + +)
        {
            Pool.execute (new Creator (plate));
            Pool.execute (new Consumer (plate));
        }

        Pool.shutdown ();
    }
</pre><pre>

Related Article

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.