Since you used the verbs "push" and "poll", it seems that you are looking for Queue not a List .
Therefore, I think you are looking for the ConcurrentLinkedQueue registered here .
This allows you to supply your UserRequest objects UserRequest it and your Poller objects for use.
Although it seems that your Poller objects will have a rather high processor load due to the open while not having wait :
public class Poller implements Runnable { Queue<String> colors = new ConcurrentLinkedQueue<String>(); public void poll() { while(this.colors.isEmpty()){ Thread.currentThread().wait(); } String color = this.colors.poll(); while(color != null) { if(color == "") {
This code needs some changes to run , but it contains almost everything you need. What he does is very simple: he continues the survey until there are no elements left. As soon as this happens, the Poller object asks the current Thread sleep, since it makes no sense to run it without elements in Queue .
public class UserRequest implements Runnable { @Override public void run() { String request; Scanner input = new Scanner(System.in); while(true) { System.out.println("Please enter request:"); request = input.nextLine(); try {
If you notice, I only added a call to notifyAll to your UserRequest class. What for? Very simple: notifyAll wakes up all wait ing Thread , which makes all Poller without elements.
As soon as it is called, Poller will wake up, check if they have Queue color elements and work with them. If Queue has no elements, they will sleep again until a UserRequest them again, etc. Etc.
source share