我怎样才能确保每条线索使用不同的独特的身份识别码, 并且该身份识别码应该在开始显示Range和结束显示Range之间。 我担心因为程序要运行60分钟, 而在60分钟之前, 所有的 ID s 都有可能被使用, 那么我应该怎么做。 我是否应该重置变量? 最佳的做法是什么?
示例: - 线索 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);
}
}