Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.Arrays;
- import java.util.Queue;
- import java.util.concurrent.LinkedBlockingQueue;
- import java.util.function.Function;
- final class Main {
- private static final class ThreadPool<T> implements Closeable {
- private final Thread[] actionThreads;
- private final Queue<T> taskQueue = new LinkedBlockingQueue<>();
- private volatile boolean working = false;
- public ThreadPool(
- final int threadsAmount,
- final Function<T, Void> action
- ) {
- actionThreads = new Thread[threadsAmount];
- for (int i = 0; i < threadsAmount; i++)
- actionThreads[i] = new Thread(() -> {
- while (working || !taskQueue.isEmpty()) {
- final var v = taskQueue.poll();
- if (v != null) action.apply(v);
- }
- });
- }
- public final void start() {
- working = true;
- Arrays.stream(actionThreads).forEach(Thread::start);
- }
- public final void push(final T elem) {
- taskQueue.offer(elem);
- }
- @Override
- public void close() {
- working = false;
- }
- }
- private static final int fib(final int number) {
- if (number < 3)
- return 1;
- var f = 1;
- var s = 1;
- for (int i = 3; i <= number; i++) {
- final var mem = s;
- s += f;
- f = mem;
- }
- return s;
- }
- public static final void main(final String[] args) throws IOException {
- final var out = System.out;
- try (final var reader = new BufferedReader(new InputStreamReader(System.in))) {
- out.print("Threads amount: ");
- try (final var pool = new ThreadPool<Integer>(
- Integer.parseInt(reader.readLine()),
- (num) -> {
- out.println(fib(num));
- return null;
- }
- )) {
- try (final var fileReader = new BufferedReader(new FileReader("file.txt"))) {
- pool.start();
- fileReader.lines().forEach((x) -> pool.push(Integer.parseInt(x)));
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment