Suppose:
- There are 10 tasks
- There are 3 threads
- There are 3 arrayLists
- Every threads related to 1 arrayList
My question is : how to manage the resources? for example, first step 3 tasks will be executed using 3 threads and 3 arrayLists. Then whenever a thread is available, the 4th task will be executed along with available arrayList. How to do that in Java? please give me reference or source code.
public class NewClass {
private Queue<Integer> availableCore = new LinkedList();
public void manage() throws InterruptedException {
ArrayList<ArrayList<Integer>> data = new ArrayList<>();
data.add(new ArrayList<>());
data.add(new ArrayList<>());
data.add(new ArrayList<>());
availableCore.add(0);
availableCore.add(1);
availableCore.add(2);
ArrayList<Calculate> allThreads = new ArrayList<>();
ExecutorService es = Executors.newWorkStealingPool(3);
int threadCount = -1;
int numOfTask = 10;
while (numOfTask > 0) {
if (!availableCore.isEmpty()) {
System.out.println(availableCore.element());
threadCount++;
int core = availableCore.remove();
allThreads.add(new Calculate(data.get(core), numOfTask, core));
es.execute(allThreads.get(threadCount));
numOfTask--;
}
}
es.shutdown();
boolean finished = es.awaitTermination(1, TimeUnit.DAYS);
System.out.println("Done\n");
for (int i = 0; i < data.size(); i++) {
System.out.println(data.get(i));
}
}
public class Calculate extends Thread {
private ArrayList<Integer> data;
private int start;
private int core;
public Calculate(ArrayList<Integer> data, int start, int core) {
this.data = data;
this.start = start;
this.core = core;
}
@Override
public void run() {
this.data.add(start);
availableCore.add(this.core);
}
public int getCore() {
return core;
}
}
}
This code above is representing my actual problem. When I tried to run several times, sometimes I got an error in "availableCore.element()". It said that availableCore is empty, but I made a condition that make sure it is not empty.
if (!availableCore.isEmpty()) {
System.out.println(availableCore.element());