Java Multithreading implements simple queues

Source: Internet
Author: User

1. Create Queue.java

public class Queue {private linkedlist<object> list = new linkedlist<object> ();p rivate final int minSize = 0 ;;p rivate Final int maxSize;p rivate atomicinteger count = new Atomicinteger (0);p ublic Queue (int size) {this.maxsize = Si Ze;} Private Final Object lock = new Object ();p ublic void put (Object o) {synchronized (lock) {while (size () = = This.maxsize) {try { Lock.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} List.add (o);//Counter increased count.incrementandget ();//Notification Wake-up lock.notify ();}} private int size () {return count.get ();} Public Object Take () {object res = NULL, synchronized (lock) {while (size () = = This.minsize) {try {lock.wait ();} catch (Interr Uptedexception e) {e.printstacktrace ();}} res = List.removefirst ();//Counter minus 1count.decrementandget (); Lock.notify ();} return res;} public static void Main (string[] args) {final queue MQ = new Queue (3), Mq.put ("a"), Mq.put ("B"), Mq.put ("C"), New Thread (new Runnable () {@Overridepublic void run () {mq.put ("G"); System.out.println ("Put1 SeccesefUL "); Mq.put (" F "); System.out.println ("Put2 secceseful");}). Start (); New Thread (New Runnable () {@Overridepublic void run () {System.out.println ("Take value =" +mq.take ())}). Start ();}}

The results of the operation are as follows:

Take value = Aput1 secceseful

When the first put is executed, the thread is blocked because the queue capacity is full. After another thread has taken, the blocked thread continues to execute the put success.

Java Multithreading implements simple queues

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.