1.2 KiB
Problem 7.1: Parallel prime number test using tasks and Executor
Implement a simple prime number test, first sequentially and then using concurrent tasks by means of
the Java Executor
framework. Your program should test all numbers n between 2 and 100.000 for
primality by simply checking all numbers d from 2 to n whether d divides n without a remainder. (Of
course there are much more efficient primality tests, but the goal here is not efficient primality tests,
but simply generating some computation load.) As its result, your program should print the number of
prime numbers found by all tasks (the correct result is 9592).
Divide the work into 100 tasks, each of them testing the next 1000 numbers. To simulate occasional
blocking due to I/O activity, make each task invoke Thread.sleep()
after checking half of its
numbers, with the sleep time chosen randomly between 1 and 100 ms (the sample solution to problem
4.2 shows an example for this).
Use a newFixedThreadPool()
, initialized with the number of available core (obtainable using
Runtime.getRuntime().availableProcessors()
). Experiment with a higher number of
threads or with a newCachedThreadPool
, too.