I am working on a project in which I need to make sure each thread get’s unique ID every time in a particular range. For example-
If number of threads is 2 and number of tasks is 10 then each thread will be performing 10 tasks. So that means 2 thread will be doing 20 tasks.
So what I am looking for something like this-
In the above example, first thread should be using id between 1 and 10 and second thread should be using id between 11 and 20.
Another example. So suppose if I have 3 thread and number of tasks as 20 then first thread should be using ID between 1 and 20 and second thread should be between 21 and 40 and third thread in between 41 and 60.
Below is the code I have so far, what it does is that it will get id as an AtomicInteger and I am getting unique id every time starting from 1.
class ThreadTask implements Runnable {
private final AtomicInteger id;
private int noOfTasks;
public ThreadTask(AtomicInteger id2, int noOfTasks) {
this.id = id2;
this.noOfTasks = noOfTasks;
}
@Override
public void run() {
while(noOfTasks > 0) {
System.out.println(id.getAndIncrement());
// And use this id for other things.
noOfTasks--;
}
}
}
public class XMPTest {
public static void main(String[] args) {
final int noOfThreads = 2;
final int noOfTasks = 10;
final AtomicInteger id = new AtomicInteger(1);
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
// queue some tasks
for (int i = 0; i < noOfThreads; i++) {
service.submit(new ThreadTask(id, noOfTasks));
}
}
}
How can I restrict this such that thread 1 should get id between 1 and 10 and second thread should get id between 11 and 20
Updated Code:-
I am trying the below code
public static void main(String[] args) {
final int noOfThreads = 2;
final int noOfTasks = 10;
//create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
// queue some tasks
for (int i = 0, int nextId = 1; i < noOfThreads; i++, nextId += noOfTasks) {
service.submit(new ThreadTask(nextId, noOfTasks));
}
}
class ThreadTask implements Runnable {
private final int id;
private int noOfTasks;
public ThreadTask(int nextId, int noOfTasks) {
this.id = nextId;
this.noOfTasks = noOfTasks;
}
public void run() {
for (int i = id; i <= noOfTasks; i++) {
System.out.println(i);
}
}
}
So for the first thread it is printing out 1 – 10 which is fine. But in the second thread, nextId is 11 and noOfTasks is 10 so my for loop going to work in the run method for second time.
Split up the range however you want in the singlethreaded code before you launch your threads, then pass the range to each thread.
For example: