fork download
  1.  
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.util.concurrent.*;
  6.  
  7. public class App {
  8. public static void main(String[] args) throws ExecutionException, InterruptedException {
  9. ExecutorService service = null;
  10. String threadName = Thread.currentThread().getName();
  11. try {
  12. service = Executors.newFixedThreadPool(6); // +1 thread for producer
  13. service.submit(new Producer(service)).get(); // Wait until producer exits
  14. } finally {
  15. if (null != service) {
  16. service.shutdown();
  17. System.out.printf("[%s] Awaiting termination...%n", threadName);
  18. try {
  19. service.awaitTermination(1, TimeUnit.HOURS);
  20. } catch (InterruptedException e) {
  21. System.err.println("Failed to terminate worker");
  22. }
  23. }
  24. }
  25. System.out.printf("[%s] Done%n", threadName);
  26. }
  27. }
  28.  
  29. class Worker implements Runnable {
  30. private String message;
  31.  
  32. public Worker(String message) {
  33. this.message = message;
  34. }
  35.  
  36. @Override
  37. public void run() {
  38. String name = Thread.currentThread().getName();
  39. ThreadLocalRandom random = ThreadLocalRandom.current();
  40. try {
  41. System.out.printf("[%s] Sending message '%s'...%n", name, message);
  42. Thread.sleep(random.nextInt(5000, 30000));
  43. System.out.printf("[%s] Message '%s' successfully sent!%n", name, message);
  44. } catch (InterruptedException e) {
  45. System.err.printf("[%s] Received interrupt signal, exiting...%n", name);
  46. }
  47. }
  48. }
  49.  
  50. class Producer implements Runnable {
  51. private ExecutorService service;
  52.  
  53. Producer(ExecutorService service) {
  54. this.service = service;
  55. }
  56.  
  57. @Override
  58. public void run() {
  59. String threadName = Thread.currentThread().getName();
  60. System.out.printf("[%s] Producer started. Enter \"exit\" to stop, or another string to " +
  61. "send it over message queue%n", threadName);
  62. try {
  63. String input = "";
  64. while (!"exit".equals(input)) {
  65. input = br.readLine();
  66. if (!"exit".equals(input)) {
  67. service.submit(new Worker(input));
  68. }
  69. }
  70. } catch (IOException e) {
  71. System.out.printf("[%s] IOException in producer, exiting...", threadName);
  72. }
  73. System.out.printf("[%s] Producer shutdown", threadName);
  74. }
  75. }
  76.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:7: error: class App is public, should be declared in a file named App.java
public class App {
       ^
1 error
stdout
Standard output is empty