各スレッドが異なる一意の ID を使用していること、およびその ID が startExistingRange と endExistingRange の間にあることを確認するにはどうすればよいですか。プログラムは 60 分間実行することになっていて、60 分前にすべての ID が使用されている可能性があるため、心配しているので、どうすればよいでしょうか。変数をリセットする必要がありますか? ベストプラクティスは何ですか?
例:- スレッド 1 は 25 を使用し、スレッド 2 は 45 などを使用します。
class ThreadTask implements Runnable {
private int id;
public ThreadTask(int id) {
this.id = id;
}
public void run() {
System.out.println("Thread " + id);
}
}
public class TestPool {
public static void main(String[] args) {
int size = 10;
int durationOfRun = 60;
int startExistingRange = 1;
int endExistingRange = 1000;
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun*60*1000);
// Running it for 60 minutes
while(System.currentTimeMillis() <= endTime) {
/* I want each thread uses different unique ID between startExistingRange
and endExistingRange */
service.submit(new ThreadTask(What should I pass
here so that each thread is using different ID));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
更新しました:-
public class TestingPool {
public static void main(String[] args) throws InterruptedException {
int size = 10;
int durationOfRun = 1;
IdPool idPool = new IdPool();
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000L);
// Getting and releasing id in while loop
while(System.currentTimeMillis() <= endTime) {
Integer id = idPool.getId();
service.submit(new ThreadTask(idPool, id));
idPool.releaseId(id);
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
class IdPool {
private final LinkedList<Integer> availableIds = new LinkedList<Integer>();
public IdPool() {
for (int i = 1; i <= 1000; i++) {
availableIds.add(i);
}
Collections.shuffle(availableIds);
}
public synchronized Integer getId() {
return availableIds.removeFirst();
}
public synchronized void releaseId(Integer id) {
availableIds.add(id);
}
}
class ThreadTask implements Runnable {
private IdPool idPool;
private int kk;
public ThreadTask(IdPool idPool, int s) {
this.idPool = idPool;
this.kk = s;
}
public void run() {
//Integer id = idPool.getId();
System.out.println("Task " + kk);
//idPool.releaseId(id);
}
}