Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use ThreadPoolExecutor thread pool correctly

Shulou Source: shulou.com Published: 2022-06-02 05:46:49 11月01日 Update

How to correctly use ThreadPoolExecutor thread pool, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Import java.util.Random

Import java.util.concurrent.*

Public class PoolTest {

Private BlockingQueue workingQueue = new ArrayBlockingQueue (10)

Private RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy ()

Private ExecutorService threadPool = new ThreadPoolExecutor (10,10,0L, TimeUnit.MILLISECONDS, workingQueue, rejectedExecutionHandler)

Private Random random = new Random ()

Public void test () {

Int size = 10

Final CountDownLatch latch = new CountDownLatch (size)

For (int I = 0; I < size; I + +) {

ThreadPool.execute (new Runnable () {

Int x = random.nextInt (10)

@ Override

Public void run () {

Try {

Plus (xmeme x)

} finally {

Latch.countDown ()

}

}

});

}

Try {

Latch.await ()

} catch (InterruptedException e) {

E.printStackTrace ()

} finally {

System.out.println ("Thread execution completed")

}

ThreadPool.shutdown ()

}

Public void plus (int x, int y) {

System.out.println ("sum =" + (x + y))

}

Public static void main (String [] args) {

PoolTest poolTest = new PoolTest ()

PoolTest.test ()

}

}

After reading the above, have you mastered how to use the ThreadPoolExecutor thread pool correctly? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Threads content methods more problems helpless for this reason skills articles experience industry information information channels channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Apple Shulou Technology Docker MariaDB