fork download
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.concurrent.*;
  5.  
  6. public class App{
  7. public final static BlockingQueue<String> queue = new ArrayBlockingQueue<String>(20);
  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. for(int i=0; i<20; ++i){queue.put("Hello");}
  14. service.submit(new Producer(service, queue)).get(); // Wait until producer exits
  15. } finally {
  16. if (null != service) {
  17. service.shutdown();
  18. System.out.printf("[%s] Awaiting termination...%n", threadName);
  19. try {
  20. service.awaitTermination(1, TimeUnit.HOURS);
  21. } catch (InterruptedException e) {
  22. System.err.println("Failed to terminate worker");
  23. }
  24. }
  25. }
  26. System.out.printf("[%s] Done%n", threadName);
  27. }
  28. }
  29.  
  30. class Worker implements Runnable {
  31. private String message;
  32.  
  33. public Worker(String message) {
  34. this.message = message;
  35. }
  36.  
  37. @Override
  38. public void run() {
  39. String name = Thread.currentThread().getName();
  40. ThreadLocalRandom random = ThreadLocalRandom.current();
  41. try {
  42. System.out.printf("[%s] Sending message '%s'...%n", name, message);
  43. Thread.sleep(random.nextInt(50, 300));
  44. System.out.printf("[%s] Message '%s' successfully sent!%n", name, message);
  45. } catch (InterruptedException e) {
  46. System.err.printf("[%s] Received interrupt signal, exiting...%n", name);
  47. }
  48. }
  49. }
  50.  
  51. class Producer implements Runnable {
  52. private final BlockingQueue<String> queue;
  53. private ExecutorService service;
  54.  
  55. Producer(ExecutorService service, BlockingQueue<String> queue) {
  56. this.service = service;
  57. this.queue = queue;
  58. }
  59.  
  60. @Override
  61. public void run() {
  62. String threadName = Thread.currentThread().getName();
  63. System.out.printf("[%s] Producer started. Enter \"exit\" to stop, or another string to " +
  64. "send it over message queue%n", threadName);
  65. while(!(Thread.currentThread().isInterrupted())){
  66. try{
  67. String message = queue.take();
  68. service.submit(new Worker(message));
  69. }catch (Exception e) {
  70. System.out.printf("[%s] IOException in producer, exiting...", threadName);
  71. }
  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:6: error: class App is public, should be declared in a file named App.java
public class App{
       ^
1 error
stdout
Standard output is empty