Java Multithreading: Producer-consumer different ways to implement __ multithreading synchronization

Source: Internet
Author: User


The problem of producer consumers is a typical thread synchronization problem.


The main implementation methods are as follows:

Wait () Notifyall ()

class queue {//Shared Queue is to save shared data for producer production and consumer consumption int value = 0;

    Boolean isempty = true; Public synchronized void put (int v) {if (!isempty) {try {System.out.pri
                Ntln ("producer Waits");
            Wait ();
            catch (Exception e) {e.printstacktrace ();
        }} value+=v;
        IsEmpty = false;
        System.out.println ("Producer Total production Quantity:" +v);
    Notify (); public synchronized int get () {if (IsEmpty) {try {System.out.prin
                TLN ("Consumer Wait");
            Wait ();
            catch (Exception e) {e.printstacktrace ();
        }} value--;
        if (value < 1) {IsEmpty = true;
        System.out.println ("Consumer consumption of one, surplus:" +value);
        Notify ();
    return value; }
}
Producer.java file
class Producer extends Thread {
    Queue q;

    Producer (Queue q)
    {
        this.q = q;
    }

    public void Run ()
    {for
        (int i = 1;i < 5; i++)
        {
            q.put (i)

}}} Class Consumer extends Thread {
    Queue q;

    Consumer (Queue q)
    {
        this.q = q;
    }
    public void Run ()
    {while
        (true)
        {
            q.get ();
}}}

Test.java file public
class <span style= "line-height:25.2000007629395px; Font-family:tahoma, Helvetica, Arial , XXFarEastFont-Arial, Sans-serif; >test</span><span style= "LINE-HEIGHT:25.2000007629395PX; Font-family:tahoma, Helvetica, Arial, XXFarEastFont-Sans-serif; >{</span> public
    static void Main (string[] args)
    {
        queue q = new Queue ();
        Producer p = new Producer (q);
        Consumer C = new Consumer (q);

        C.start ();
        P.start ();
    }
Java.util.concurrent.BlockingQueue implementation in Blockingqueue There are two important blocking methods: Put () and take ()


Put (): The production of goods, when the production of goods have been filled with warehouses, into the blocked form
state, awaken the consumer to tuneUse the Take () method.

take (): After the consumption of goods, into the blocking state, wake-up producer.


The implementations of these two methods use the lock and condition
Package Kevin;
Import Java.util.concurrent.ArrayBlockingQueue;
Import Java.util.concurrent.BlockingQueue;

Import Java.util.concurrent.TimeUnit; /** * A simple producer-consumer demo * * @author Kevinjom */public class Blockingqueuedemo {public static void Main (string[) arg
	s) {new Blockingqueuedemo (). Go (); private void Go () {//Here's a simple blockingqueue implementation, which is based on the producer-consumer model, which has two important blocking methods/put () and take (), and the implementations of these two methods use lock and Conditi
		On, the specific implementation please refer to API blockingqueue<string> queue = new arrayblockingqueue<string> (10); thread T1 = new Thread (new Producer (queue,, "Peak")); Producer threads, come, produce some I//can/play bar, and be faster than the Nike production thread t2 = new Thread (New Producer (Queu E, 1000, "Nike"); The second producer threads thread t3 = new Thread (new Customer (queue));
		Consumer thread T1.start ();
		T2.start ();
	T3.start ();
		Private class Producer implements Runnable {private blockingqueue<string> queue; private int timeout; The time to produce a product is suspended after private String category; Just upMark Product Action Public Producer (blockingqueue<string> queue, int timeout, String category) {super ();
			This.queue = queue;
			This.timeout = timeout;
		this.category = category; @Override public void Run () {while!
					Thread.CurrentThread (). isinterrupted ()) {The try {//Put () method is also a blocking method, and if the queue is full, the method blocks together until//the space is back up in the queue
				Queue.put ("Product" + category);
				catch (Interruptedexception E1) {e1.printstacktrace ();
					try {TimeUnit.MILLISECONDS.sleep (timeout);//pause timeout millisecond} catch (Interruptedexception e) for each production
				E.printstacktrace ();

		'}}} private class Customer implements Runnable {private blockingqueue<string> queue;
			Public Customer (blockingqueue<string> queue) {super ();
		This.queue = queue; @Override public void Run () {while!
				Thread.CurrentThread (). isinterrupted ()) {try {System.out.println ("Product got:" + queue.take ()); catch (InterruptedexceptiOn E1) {e1.printstacktrace (); try {//pause 10 milliseconds, this is primarily to prove that take () is a blocking method and that if there is no element in the Blockingqueue//, it will block together until there is an element in the queue Timeunit.millisecon
				Ds.sleep (10);
				catch (Interruptedexception e) {e.printstacktrace ();
 }
			}

		}

	}

}


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.