Java 将旧线程池代码升级到新的并发类

Java 将旧线程池代码升级到新的并发类,java,multithreading,concurrency,threadpool,daemon,Java,Multithreading,Concurrency,Threadpool,Daemon,我正在更新一些我很久没有接触过的旧Java代码。我的问题是,现在做线程池的最佳方法是什么 之前我使用了并发util类的: import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer; import EDU.oswego.cs.dl.util.concurrent.PooledExecutor; 然而,我不认为这是最好的方式,因为我现在正在更新到Java7 以下是我的代码片段: Static PooledExecuter pooledExecute

我正在更新一些我很久没有接触过的旧Java代码。我的问题是,现在做线程池的最佳方法是什么

之前我使用了并发util类的:

import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
然而,我不认为这是最好的方式,因为我现在正在更新到Java7

以下是我的代码片段:

Static PooledExecuter pooledExecuter = null;

在run方法中,我还调用pooledExecuter.execute(新TestClass)

基本上,我想知道我现在应该用哪种方式处理线程池


任何帮助都将不胜感激。

我不确定
BoundedBuffer
是如何发挥作用的,但我相信您只需要说:

threadPool = Executors.newFixedThreadPool(maxThreadPoolSize, new ThreadFactory() {
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true);
        return thread;
    }
});
BoundedBuffer
可以被使用
LinkedBlockingQueue
在内部创建的
BlockingQueue
替换

如果希望对保持活动设置(etc)进行更细粒度的控制,那么可以直接调用

public ThreadPoolExecutor(int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue,
    ThreadFactory threadFactory)
public ThreadPoolExecutor(int-corePoolSize,
int maximumPoolSize,
长时间,
时间单位,
阻塞队列工作队列,
螺纹工厂(螺纹工厂)
比如:

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;
        }
    });
threadPool=newthreadpoolexecutor(initialCapactiy,maxThreadPoolSize,
时间,TimeUnit.SECONDS,新LinkedBlockingQueue(),
新螺纹工厂(){
公共线程newThread(可运行的r){
螺纹=新螺纹(r);
setDaemon(true);
返回线程;
}
});

您可能应该使用
ExecutorService
,您可以从中的众多方便方法之一构造该服务,包括用于指定有界队列等的方法来插入项目


我在您的代码中看到许多拼写错误,例如
Static
关键字(大写S)无效,
PooledExecutor
拼写不同。您确定要编译吗?

您可以使用Java并发UTIL。查看用于处理线程池的Executor框架

或者,如果使用Spring,请查看TaskExecutor


如果您在JavaEE应用程序服务器中运行代码,您可能需要查看服务器的文档,以找到使用线程池的最佳方法

java7引入了ForkJoinPool。关于何时使用它的文章。

与该问题的链接是什么?
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;
        }
    });