I have a few threads running simultaneously, and whenever each starts, I would like each individual to get one item from the String Arraylist, and hold onto that particular unique item until it completes. What would be a good way to implement this? In the run method in a thread, I though about String uniqueItem = itemList.get(k); and k++ after getting it, but the thread will run that particular line over and over, and the next time it runs it again, it will be holding onto a different unique item. Is there a way to make each thread get one item only once, and the next gets what's available, and so on, and hold onto that one item.
ItemHolder thread = new ItemHolder();
private ArrayList<String> itemList = new ArrayList<String>(); //Contains 4 Strings (e.g. Apple, Orange, Watermelon, Pear)
int k = 0;
ExecutorService executor = Executors.newFixedThreadPool(4); //E.g. run 4 Threads
executor.execute(thread);
class ItemHolder extends Thread{
public void run(){
String uniqueItem = itemList.get(k); //Would like the first thread to grab the first index item, 0, and hold onto it until it finishes. But other thread that runs the same, I would like it to have index item, 1, and hold onto that, and the other thread to have whatever is available and so on.
k++; //This would be a problem
}
}