Config File
ThreadSize = 10 StartRange = 1 EndRange = 1000
I have a config file above in which I have number of threads I want to use and the client instance is able to use ID range from 1 to 1000 and suppose the client threads is set at 10, so each thread would have range of 100 id’s(basically by dividing end range with thread size) that it can use without stepping on other threads. so What I want is that each thread should use 100 id’s from that range without stepping on other threads- for example
Thread1 will use 1 to 100 (id's) // generate a random number between 1 to 100 and keep on printing values until it has generated all the random values between 1 to 100 Thread2 will use 101 to 200 (id's) // generate a random number between 101 to 200 and keep on printing values until it has generated all the random values between 101 to 200 Thread3 will use 201 to 300 (id's) // generate a random number between 201 to 300 and keep on printing values until it has generated all the random values between 201 to 300 ----- ---- Thread10 will use 901 to 1000 // generate a random number between 901 to 1000 and keep on printing values until it has generated all the random values between 901 to 1000
I know how to write a multithreading program, but not sure how should I divide the range between various threads.
public static void main(String[] args) { for (int i = 1; i <= threadSize; i++) { new Thread(new ThreadTask(i)).start(); } } class ThreadTask implements Runnable { private int id; public ThreadTask(int id) { this.id = id; } public synchronized void run() { } }
Advertisement
Answer
Each thread gets N = (EndRange - StartRange + 1) / ThreadSize
numbers.
Thread number i
gets range (StartRange + i*N) - (StartRange + i*N + N - 1)
.
In your example N = (1000 - 1 + 1) / 10 = 100
.
Thread i = 0
would get range (1 + 0*100) - (1 + 0*100 + 100 - 1)
= 1 - 100
Thread i = 1
would get range (1 + 1*100) - (1 + 1*100 + 100 - 1)
= 101 - 200
…