简体   繁体   中英

How to inform other objects(how to “close” queue) that there will be no more elements in ArrayBlockingQueue,

I have an ArrayBlockingQueue<String> queue; and an Author object puts elements in there:

public static final String END = "db8097f51282a0188e988d6bfa994430258e24ce";

[...]

for (String text : texts) {
            queue.put(text);
            Thread.sleep(300);
        }
queue.put(END);

and a Printer objects which takes elements from the qeue and prints them on the console:

 String text;
 do {
     text = queue.take();
     if (!text.equals(Author.END))
            System.out.println(text);
} while (tekst != Author.END);

I wanted inform Printer object that there will be no more elements put into the qeue. I cannot pass null into ArrayBlockingQueue so I decided to pass very unusual String inside. I think it is bad solution.

Can I somehow close the ArrayBlockingQueue ?

your solution seems fine. Two points to consider:

  • If you're going to have more than one Printer reading values off of the same queue you may want the printer to push the END value back into the queue so that other Printers will get a chance to see it
  • Consider storing not just a plain string but instead an object of a class which you define. This class can have a string field to carry the actual payload and additional boolean field such as 'isEnd`. this will make the distinction between regular items and end-of-queue item more explicit in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM