Java multi-thread producer-consumer

Source: Internet
Author: User

 Public classProduct {PrivateString Lock;  PublicProduct (String lock) { This. Lock =lock; }     Public voidSetValue () {Try {            synchronized(lock) {if(! ValueObject.value.equals ("") ) {lock.wait (); } String Value=system.currenttimemillis () + ""; System.err.println ("Set" + "++++++++++++++++++++++"); Valueobject.value=value; Thread.Sleep (1000);            Lock.notify (); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }} Public classConsumer {PrivateString Lock;  PublicConsumer (String lock) { This. Lock =lock; }     Public voidGetValue () {Try {            synchronized(lock) {if(ValueObject.value.equals ("") ) {lock.wait (); } System.err.println ("Get" + "---------------------------"); Valueobject.value= "";            Lock.notify (); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }} Public classThreadpextendsThread {Privateproduct product;  PublicTHREADP (product product) { This. Product =product; } @Override Public voidrun () { while(true) {product.setvalue (); }    }} Public classThreadcextendsthread{PrivateConsumer Consumer;  PublicTHREADC (Consumer Consumer) { This. Consumer =consumer; } @Override Public voidrun () { while(true) {consumer.getvalue (); }    }} Public classValueobject { Public StaticString value = "";} Public classTest { Public Static voidMain (string[] args) {String lock=NewString (""); Product Product=NewProduct (lock); Consumer Consumer=NewConsumer (lock); THREADP P=Newthreadp (product); THREADC C=NewTHREADC (consumer);        P.start ();    C.start (); }}

Output is set and get alternating print

Java multi-thread producer-consumer

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.