Java multi-thread production and consumption patterns
Source: Internet
Author: User
/* @author shijin * producer and consumer model, to ensure that the following: * 1 at the same time only one producer production Production method Lock sychronized * 2 only one consumer consumer in the same time Consumption method Lock sychronized * 3 producer production while consumers can not consume production method lock sychronized * 4 consumer consumption at the same time producers can not produce consumption methods add lock sychronized * 5 space time consumers can not continue to consume consumption before the cycle to judge whether it is empty, empty words will wait for the thread, release the lock allow other synchronous methods to execute * 6 The producer cannot continue to produce when the space is full pre-production cycle to determine whether it is full, full if the thread wait, release the lock allow other synchronous methods to execute */ //Main class class producerconsumer { public static void main (String[] args) { stackbasket s = new stackbasket ();      producer p = new producer (s); consumer c = new consumer (s); thread tp = new thread (p); thread tc = new thread (c); tp.start (); tc.start (); } } // Class mantou { private int id; mantou (int id) { this.id = id; } public string tostring () { return "Mantou &NBSP: " + id; } } //shared stack space class stackbasket { mantou sm[] = new Mantou[6]; int index = 0; /** * show Production method . * show The method is synchronous, holding method lock; * show First cycle to judge full No, full words make the thread wait, release the Sync method lock, allow consumption; * show when dissatisfied first wake up the waiting consumption method, But you can only let it in., * show etc production End release Sync method lock consumption can hold the lock for consumption * @param m elements * @return No return value */ public synchronized void push (Mantou m) { try{ while (Index
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