Java Blocking queue

Source: Internet
Author: User

It's a bit of a hassle to deal with messages, so make sure all sorts. In order to ensure the successful delivery of the message 100%, the author has made some improvements on the basis of the previous. Multiple threads are used to send the information repeatedly.

So check a lot of things about thread safety, but also see the blocking queue, found that this mode is very good, but I do not use the current.

There is a lot of talk about this, blocking this, that is, when there is no data in the queue, the thread will wait for it to read. When the data in the queue is full, the thread waits for the data to be added.

There is an example of a very vivid image, put eggs inside the plate, can only put a fixed number of. There were no eggs in the plate and could not be taken out. When the plate is full, it cannot be put in. Until it is taken out, it can be put.

The code below is set up with a plate of up to 10 eggs:

 PackageCom.thread.two;Importjava.util.ArrayList;Importjava.util.List; Public classPlate {List<Object> eggs=NewArraylist<object>(); Public synchronizedObject Getegg () { while(Eggs.size () ==0){            Try{wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }} Object Egg=NULL;  for(inti = 0; I < 10; i++) {Egg=Eggs.get (i); System.out.println ("Get the eggs ..."); }        //Object egg=eggs.get (0);eggs.clear ();        Notify (); //System.out.println ("Get the eggs ...");        returnEgg; }         Public synchronized voidPutegg (Object egg) { while(Eggs.size () >9){            Try{wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }} eggs.add (egg);        Notify (); System.out.println ("Put the eggs ..."); }        Static classAddthreadextendsthread{PrivatePlate Plate; PrivateObject egg=NewObject ();  PublicAddthread (Plate Plate) { This. plate=plate; }         Public voidrun () { for(inti = 0; i < 1000; i++) {Plate.putegg (egg); }        }    }        Static classGetThreadextendsthread{PrivatePlate Plate;  PublicGetThread (Plate Plate) { This. plate=plate; }         Public voidrun () { for(inti = 0; i < 1000; i++) {Plate.getegg (); }        }    }         Public Static voidMain (string[] args)throwsinterruptedexception {Plate Plate=NewPlate (); Thread Add=NewThread (NewAddthread (plate)); Thread Get=NewThread (NewGetThread (plate));        Add.start ();        Get.start ();        Add.join ();        Get.join (); System.out.println ("End of Test"); }    }

This example is very image, using threads to achieve the above mentioned.

Java now has a concurrent package, there are many ready-to-use classes, many are thread-safe, so, like the above write put or get, do not need to write their own synchronization method, these classes have been packaged.

Here is an example of a arrayblockingqueue, similar to what is implemented above.

The first is two threads, put and get, respectively.

Threadput:

 PackageCom.thread.three;ImportJava.util.concurrent.ArrayBlockingQueue; Public classThreadputImplementsrunnable{PrivateArrayblockingqueue<string> abq=NULL;  PublicThreadput (arrayblockingqueue<string>ABQ) {         This. abq=ABQ; }     Public voidrun () {//TODO auto-generated Method Stub         while(true) {System.out.println ("To save data to the queue"); Try{Thread.Sleep (1000); Abq.put ("Hi"); System.out.println ("After deposit, the data is:" +abq.size ()); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }}

Threadget:

 PackageCom.thread.three;ImportJava.util.concurrent.ArrayBlockingQueue; Public classThreadgetextendsThread {arrayblockingqueue<String> abq=NULL;  PublicThreadget (arrayblockingqueue<string>ABQ) {         This. abq=ABQ; } @Override Public voidrun () {//TODO auto-generated Method Stub         while(true){            Try{Thread.Sleep (2000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("I'm going to fetch data from the queue."); String msg=NULL; if(Abq.size () >0) {msg=Abq.remove (); } System.out.println ("The data obtained in the queue is:" +msg+ ", and there is a total in the queue:" +abq.size ()); }    }}

Test class:

 Public class Arrayblockqueueapp {        publicstaticvoid  main (string[] args) {        Executorservice  es=executors.newcachedthreadpool ();        Arrayblockingqueue<String> abq=new arrayblockingqueue<string> (ten);        Threadget tget=new  threadget (ABQ);        Thread TPut=new thread (new  threadput (ABQ));        Es.execute (tget);        Es.execute (TPut);    }}

These queues are good for putting messages.

 

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.