
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.*;

public class App {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = null;
        String threadName = Thread.currentThread().getName();
        try {
            service = Executors.newFixedThreadPool(6); // +1 thread for producer
            service.submit(new Producer(service)).get(); // Wait until producer exits
        } finally {
            if (null != service) {
                service.shutdown();
                System.out.printf("[%s] Awaiting termination...%n", threadName);
                try {
                    service.awaitTermination(1, TimeUnit.HOURS);
                } catch (InterruptedException e) {
                    System.err.println("Failed to terminate worker");
                }
            }
        }
        System.out.printf("[%s] Done%n", threadName);
    }
}

class Worker implements Runnable {
    private String message;

    public Worker(String message) {
        this.message = message;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        try {
            System.out.printf("[%s] Sending message '%s'...%n", name, message);
            Thread.sleep(random.nextInt(5000, 30000));
            System.out.printf("[%s] Message '%s' successfully sent!%n", name, message);
        } catch (InterruptedException e) {
            System.err.printf("[%s] Received interrupt signal, exiting...%n", name);
        }
    }
}

class Producer implements Runnable {
    private ExecutorService service;

    Producer(ExecutorService service) {
        this.service = service;
    }

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.printf("[%s] Producer started. Enter \"exit\" to stop, or another string to " +
                "send it over message queue%n", threadName);
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String input = "";
            while (!"exit".equals(input)) {
                input = br.readLine();
                if (!"exit".equals(input)) {
                    service.submit(new Worker(input));
                }
            }
        } catch (IOException e) {
            System.out.printf("[%s] IOException in producer, exiting...", threadName);
        }
        System.out.printf("[%s] Producer shutdown", threadName);
    }
}
