fork download
  1. import java.util.Random;
  2. import java.util.concurrent.CountDownLatch;
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.TimeUnit;
  6.  
  7. public class Main
  8. {
  9. public static void main (String[] args) throws java.lang.Exception
  10. {
  11. CountDownLatch latch = new CountDownLatch(3);
  12. ExecutorService exec = Executors.newCachedThreadPool();
  13.  
  14. exec.execute(new WaitingTask(latch));
  15.  
  16. exec.execute(new Workers(latch,1));
  17. exec.execute(new Workers(latch,2));
  18. exec.execute(new Workers(latch,3));
  19.  
  20. }
  21. }
  22.  
  23. class WaitingTask implements Runnable {
  24. private CountDownLatch latch;
  25.  
  26. public WaitingTask(CountDownLatch latch) {
  27. this.latch = latch;
  28. }
  29.  
  30. public void run() {
  31. try {
  32. System.out.println(this + ": waiting for other tasks to end");
  33. latch.await();
  34. System.out.println(this + ": I AM FREE!!!");
  35. } catch (InterruptedException e) {
  36. //TODO
  37. }
  38. }
  39.  
  40. public String toString() {
  41. return "WaitingTask";
  42. }
  43. }
  44.  
  45. class Workers implements Runnable {
  46. private Random random = new Random();
  47. private final int id;
  48. private CountDownLatch latch;
  49.  
  50. public Workers(CountDownLatch latch, int id) {
  51. this.latch = latch;
  52. this.id = id;
  53. }
  54.  
  55. public void run() {
  56. try {
  57. System.out.println(this + ": doing some work");
  58. TimeUnit.MILLISECONDS.sleep(random.nextInt(2000));
  59.  
  60. latch.countDown();
  61. } catch (InterruptedException e) {
  62. //TODO
  63. }
  64. }
  65.  
  66. public String toString() {
  67. return String.format("Worker %3d", id);
  68. }
  69. }
Time limit exceeded #stdin #stdout 5s 381632KB
stdin
Standard input is empty
stdout
WaitingTask: waiting for other tasks to end
Worker   1: doing some work
Worker   2: doing some work
Worker   3: doing some work
WaitingTask: I AM FREE!!!