我正在更新一些我多年没有碰过的旧Java代码。我的问题涉及现在进行线程池的最佳方法是什么?
以前我使用的是并发工具类:
import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
但是我不认为这是我现在更新到Java 7的最好方法。
这是我的代码段:
Static PooledExecuter pooledExecuter = null;
...
private ThreadPoolExample(Int initialCapactiy, int initThreadPoolSize,
int maxThreadPoolSize, int minThreadPoolSize,
int time) throws Exception
{
pooledExecuter = new PooledExecuter(new BoundedBuffer(initialCapactiy), maxThreadPoolSize);
pooledExecuter.setMinimumPoolSize(minThreadPoolSize);
pooledExecuter.setKeepAliveTime(1000 * time);
pooledExecuter.waitWhenBlocked();
pooledExecuter.createThreads(initThreadPoolSize)
//setup thread
this.thread = new Thread(this);
this.thread.setName("threadtest");
try
{
this.thread.setDaemon(this)
}
catch (Exception e)
{
}
}
在我的run方法中,我也调用pooledExecuter.execute(new TestClass)
基本上,我想知道我现在应该以哪种方式处理线程池?
非常感谢任何帮助。
答案 0 :(得分:2)
我不确定BoundedBuffer
是如何发挥作用的,但我相信你只需说:
threadPool = Executors.newFixedThreadPool(maxThreadPoolSize, new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
BoundedBuffer
可能会被BlockingQueue
取代,而LinkedBlockingQueue
是使用public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
在内部创建的。
如果您想要对保持活动设置(等)进行更精细的控制,那么您可以直接调用ThreadPoolExecutor
constructor。
threadPool = new ThreadPoolExecutor(initialCapactiy, maxThreadPoolSize,
time, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
类似的东西:
{{1}}
答案 1 :(得分:1)
您应该使用ExecutorService
,您可以使用Executors
中的众多便捷方法之一构建Static
,包括指定有界队列的方法等,以便插入项目。
我发现您的代码中存在大量拼写错误,例如PooledExecutor
关键字(使用大写字母S)无效且{{1}}拼写不同。你确定要编译吗?
答案 2 :(得分:1)
您可以使用Java Concurrency Utils。查看Executor框架以使用线程池。
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executor.html http://www.vogella.com/articles/JavaConcurrency/article.html#threadpools
或者,如果您使用Spring,请查看TaskExecutor。
http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html
如果您在Java EE应用程序服务器中运行代码,则可能必须查看服务器的文档以找出使用线程池的最佳方法。
答案 3 :(得分:-1)
Java 7引入了ForkJoinPool。关于何时使用它的文章here。