Java Multithreaded shared variables

Source: Internet
Author: User

Import Java.util.linkedlist;import Java.util.list;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class PC {private static Final lock lock = new Reentrantlock ();p rivate static final Condition empty = Lock.newcondition ();p rivate static final Cond ition full = lock.newcondition ();p rivate static final list<integer> List = new linkedlist<> ();p rivate static I  NT size = 0;private static int maxSize = 5;private static int product = 1;public static void put () {lock.lock (); try {while (size = = maxSize) {empty.await ();} List.add (product); size++; System.out.println ("put" + product);p roduct++;full.signal ();} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.unlock ();}} public static void Take () {lock.lock (); try {while (size = = 0) {full.await ();} int tep = list.remove (0); size--; System.out.println ("take" + Tep); empty.signal ();} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.unlock ();}} Class Producer implements Runnable {@Overridepublic void Run () {for (int i = 1; i <; i++) {put (); try {thread.sleep (1 00);} catch (Interruptedexception e) {e.printstacktrace ();}}}} Class Consumer implements Runnable {@Overridepublic void Run () {for (int i = 1; i <, i++) {take (); try {thread.sleep ( 1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}} public static void Main (string[] args) {pc PC = new PC (); new Thread (Pc.new Producer ()). Start (); New Thread (Pc.new Consumer ( ). Start (); New Thread (Pc.new Producer ()). Start (); New Thread (Pc.new Consumer ()). Start ();}}

Put 1take 1put 2take 2put 3put 4put 5put 6put 7take 3take 4put 8put 9take 5take 6put 10put 11take 7take 8put 12put 13take 9take 10put 14put 15take 11take 12put 16put 17take 13take 14put 18take 15take 16take 17take 18

Java Multithreaded shared variables

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.