Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run static method from a thread pool in java

What is the best way to run a static method in several threads, using a thread pool? Also I trying to pass an argument to the static method. something like

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

}

and from a main:

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

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

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

}

Thanks!

like image 593
yken Avatar asked Apr 18 '26 03:04

yken


1 Answers

Have a look at the documentation for java.util.concurrent.Executors. It should meet your needs. Here is a simple example of using it:

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());
    }
}
like image 185
Mike Clark Avatar answered Apr 19 '26 16:04

Mike Clark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!