I have a while loop that checks if an arraylist containing commands for the program to execute is empty. Obviously it does things if not empty, but if it is right now I just have a Thread.sleep(1000) for the else. That leaves anything that interacts with it rather sluggish. Is there any way to get the thread it runs on to block until a new command is added? (It runs in it’s own thread so that seems to be the best solution to me) Or is there a better solution to this?
Share
You can use
wait()andnotify()to have the threads that add something to the list inform the consumer thread that there is something to be read. However, this requires proper synchronization, etc..But a better way to solve your problem is to use a
BlockingQueueinstead. By definition, they are synchronized classes and the dequeuing will block appropriately and wakeup when stuff is added. TheLinkedBlockingQueueis a good class to use if you want your queue to not be limited. TheArrayBlockingQueuecan be used when you want a limited number of items to be stored in the queue (orLinkedBlockingQueuewith an integer passed to the constructor). If a limited queue thenqueue.add(...)would block if the queue was full.