java - 从java中的线程池运行静态方法

标签 java multithreading threadpool static-methods

使用线程池在多个线程中运行静态方法的最佳方法是什么? 我也试图将一个参数传递给静态方法。像

Class A{
 public static runTask(int i){
   ....
 }

}

从一个主要的:

ThreadPool pool = new ThreadPool(5, "poolname");

for(int i=1; i<10; i++){

   A.runTask(i) // but on a new thread...

}

谢谢!

最佳答案

查看 java.util.concurrent.Executors 的文档。它应该满足您的需求。这是一个使用它的简单示例:

public class ExecutorServiceTest {
    static ExecutorService threadPool = Executors.newCachedThreadPool();

    public static void main(String[] args) throws Exception {
        // Queue 10 executions of someTask into the threadPool 
        for(int i = 0; i < 10; i++) {
            runSomeTaskInThreadPool();
        }
        // the shutdown method causes the executor to:
        // 1. stop accepting new tasks, and
        // 2. allow previously queued jobs to complete, and
        // 3. shut down all pooled threads once all jobs are complete  
        threadPool.shutdown();
        // block until the threadPool has finished shutting down,
        // which indicates that all tasks have finished executing
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    }

    private static void runSomeTaskInThreadPool() {
        Future future = threadPool.submit(new Runnable() {
            public void run() {
                someTask();
            }
        });
        // TODO: Maybe keep track of futures to monitor success/failure of task
    }

    static AtomicInteger counter = new AtomicInteger();
    public static void someTask() {
        System.out.println("someTask: " + counter.incrementAndGet() 
                + " on thread: " + Thread.currentThread());
    }
}

关于java - 从java中的线程池运行静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4254550/

相关文章:

java - 从java中的另一个类访问对象?

java - 如何在olingo中读取具有复杂属性的实体集合?

c - 多线程 printf() 与 c 中的信号量

c# - 如何制作具有连续 ID 的线程

java - 即使使用线程池,多线程时许多短期任务也会变慢

python-3.x - 如何使用 getattr 进行多线程,每个属性一个线程?

java - 如何从java中的字符数组中获取替代字符?

java - Android:模糊位图,同时确保文本可读性

java - 我应该将 boolean 字段设置为易变的吗?

java - tomcat:WAITING条件线程