如何确保每个线程使用不同的唯一 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);
}
}