I’m just learning a bit about threads in Java and I was wondering if some one could help me out.
I have created a list of 10 integers. What I want to do is have multiple threads go in, grab the integer at index 0, print it and remove it. I want this to happen until there are no more numbers in the list. This is my code so far.
public class SlothTest implements Runnable{
static ArrayList<Object> test = new ArrayList<>();
static int listSize;
public static void main(String[] args) {
for (int i = 0; i < 10; i++){
test.add(i);
}
SlothTest runner = new SlothTest();
Thread alpha = new Thread(runner);
Thread beta = new Thread(runner);
alpha.setName("Alpha thread");
beta.setName("Beta thread");
alpha.start();
beta.start();
}
@Override
public void run() {
listSize = test.size();
while (listSize > 0){
getLink();
}
}
private synchronized void getLink(){
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " printed " + test.indexOf(listSize - 1));
test.remove(0);
listSize = test.size();
}
}
Can someone help point out everything I’m doing wrong, it’s probably a lot.
The test of
listSize > 0is not properly synchronized. The list could be non-empty when the check is performed but then actually be empty by the time the thread callsgetLink(). It would probably be easier to havegetLink()returnbooleaninstead of void wheretruewould indicate that the list is empty andfalsewould indicate that it is not then each thread could just keep calling the method until it returnsfalse. You would also have to check that the list is not empty at the top of ofgetLink()before you try to remove an item.