【发布时间】:2012-06-01 23:26:23
【问题描述】:
当我在我的一个项目中使用它时,我开始从 Java Doc 中阅读更多关于 ThreadPoolExecutor 的信息。那么谁能解释一下这条线实际上是什么意思?-我知道每个参数代表什么,但我想从这里的一些专家那里以更一般/外行的方式理解它。
ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10, true), new
ThreadPoolExecutor.CallerRunsPolicy());
更新:- 问题陈述是:-
每个线程使用 1 到 1000 之间的唯一 ID,并且程序必须运行 60 分钟或更长时间,因此在这 60 分钟内,所有 ID 都可能完成,因此我需要再次重用这些 ID。所以这是我使用上面的执行器编写的下面的程序。
class IdPool {
private final LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
public IdPool() {
for (int i = 1; i <= 1000; i++) {
availableExistingIds.add(i);
}
}
public synchronized Integer getExistingId() {
return availableExistingIds.removeFirst();
}
public synchronized void releaseExistingId(Integer id) {
availableExistingIds.add(id);
}
}
class ThreadNewTask implements Runnable {
private IdPool idPool;
public ThreadNewTask(IdPool idPool) {
this.idPool = idPool;
}
public void run() {
Integer id = idPool.getExistingId();
someMethod(id);
idPool.releaseExistingId(id);
}
// This method needs to be synchronized or not?
private synchronized void someMethod(Integer id) {
System.out.println("Task: " +id);
// and do other calcuations whatever you need to do in your program
}
}
public class TestingPool {
public static void main(String[] args) throws InterruptedException {
int size = 10;
int durationOfRun = 60;
IdPool idPool = new IdPool();
// create thread pool with given size
ExecutorService service = new ThreadPoolExecutor(size, size, 500L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(size), new ThreadPoolExecutor.CallerRunsPolicy());
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000L);
// Running it for 60 minutes
while(System.currentTimeMillis() <= endTime) {
service.submit(new ThreadNewTask(idPool));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
我的问题是:- 就性能而言,此代码是否正确?还有什么我可以在这里使它更准确?任何帮助将不胜感激。
【问题讨论】:
-
我看不出你的代码有什么问题,除了可能在你的“运行”方法中有一个 try/finally 以确保 id 总是被释放(当你有一个更复杂的代码时“一些方法”)。
-
@Matt,感谢您的评论,所以 someMethod 必须同步?或不?就我而言,我已经同步了。
-
idPool.releaseExistingId(id);应该出现在 finally 块中吧?
标签: java multithreading threadpool executorservice