new to multithreading here please bear with me. I'm trying to run 2 threads which remove items from a list of tasks (10 tasks in total) until the taskList is empty.
What i have so far is:
Main method:
public static void main(String[] args) {
List<Task> taskList = new ArrayList<Task>();
List<Thread> threadList = new ArrayList<Thread>();
for (int i = 1; i <= 10; i++) {
taskList.add(new Task("some details");
}
TaskManager manager = new TaskManager();
gestor.setTaskList(taskList);
Thread t1 = new Thread(taskManager);
Thread t2 = new Thread(taskManager);
threadList.add(t1);
threadList.add(t2);
if(threadList.size() > 0){
for (Thread thread : threadList){
thread.start();
}
}
for (Thread thread : threadList){
try {
thread.join();
} catch (InterruptedException e) {
System.out.println("thread " + Thread.currentThread().getName() + " was interrupted");
}
}
System.out.println("END OF MAIN");
}
Task Manager class:
public class TaskManager implements Runnable {
private List<Task> availableTasks;
private Random random = new Random();
public void setAvailableTasks(List<Task> availableTasks) {
this.availableTasks = availableTasks;
}
@Override
public void run() {
while (!availableTasks.isEmpty()) {
takeTask();
}
}
public void takeTask() {
try {
Thread.sleep(1000);
int index = random.nextInt(availableTasks.size());
Task task = availableTasks.get(index);
printDetails(task);
availableTasks.remove(task);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printDetails(Task task) {
//here it should print the details to the console
}
}
The thing is, it either runs 2 times or it's always the same thread running 10 times. I know it's probably a silly question but I hope someone can clarify it! Thanks in advance
Edit: I was able to make it work using @Lidae's suggestion
Take task method edited like so:
public void takeTask() {
try {
Thread.sleep(1000);
synchronized (this) {
if (!availableTasks.isEmpty()) {
int index = random.nextInt(availableTasks.size());
Task task = availableTasks.get(index);
printDetails(task);
availableTasks.remove(task);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}