New to Java here. Just confused on the inconsistent output of this sample program. Sometimes, task_queue.size() is zero and sometimes it is not. What could be the reason for this?
Output:
t4 : [Task9999] has been executed
t1 : [Task9969] has been executed
waiting...
finished
Number of Tasks left : 4
Process finished with exit code 0
import java.util.ArrayList;
public class TaskExecutor implements Runnable {
private ArrayList<String> arr;
public TaskExecutor(ArrayList<String> arr) {
this.arr = arr;
}
@Override
public void run() {
String task;
while (arr.size() != 0 && (task = arr.remove(0))!=null) {
System.out.println(Thread.currentThread().getName() + " : [" + task + "] has been executed");
}
}
}
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws InterruptedException {
ArrayList<String> task_queue = new ArrayList<>();
for(int i = 0; i < 10000; i++) {
task_queue.add("Task" + i);
}
Thread t1 = new Thread(new TaskExecutor(task_queue));
Thread t2 = new Thread(new TaskExecutor(task_queue));
Thread t3 = new Thread(new TaskExecutor(task_queue));
Thread t4 = new Thread(new TaskExecutor(task_queue));
Thread t5 = new Thread(new TaskExecutor(task_queue));
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t4.setName("t4");
t5.setName("t5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
System.out.println();
while(t1.isAlive() || t2.isAlive() || t3.isAlive() || t4.isAlive() || t5.isAlive()) {
}
System.out.println("waiting...");
Thread.currentThread().sleep(2000);
System.out.println("finished");
System.out.println("Number of Tasks left : " + task_queue.size());
}
}