Home
Cloud
Big Data
CI
Install
Samples
Java
Ubuntu
Maven
Archive
Java
|
Executors::newFixedThreadPool
Maven - POM Configuration
Example: ExecutorService::execute(Runnable)
Maven - POM Configuration
Before you can use the java concurrent API, you need to add some dependencies to your "
pom.xml
" file.
Here's the minimal dependencies needed in order for the following examples to work:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency>
Example: ExecutorService::execute(Runnable)
final String namingPattern = "_newFixedThreadPool"; final BasicThreadFactory.Builder builder = new BasicThreadFactory.Builder(); final BasicThreadFactory basicThreadFactory = builder.namingPattern(namingPattern).daemon(true).build(); final ExecutorService executorService = Executors.newFixedThreadPool(2, basicThreadFactory); IntStream.iterate(0, i -> i + 1).limit(5).forEach(t -> executorService.execute(() -> { // simulate a random time-consuming code try { Thread.sleep(new Random().nextInt(100) + 1); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ": " + t); })); executorService.awaitTermination(200l, TimeUnit.MILLISECONDS); executorService.shutdown();
Output:
_newFixedThreadPool: 1 _newFixedThreadPool: 0 _newFixedThreadPool: 2 _newFixedThreadPool: 4 _newFixedThreadPool: 3
© 2010-2022
mti
tek