fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. class Ideone {
  7. public static void main(String[] args) {
  8. new Ideone();
  9. }
  10.  
  11. public Ideone() {
  12. DummyBuffer<String> buf = new DummyBuffer<String>(new ArrayList<String>(), 5);
  13.  
  14. Thread prod = new Thread(new Producer(buf));
  15. Thread cons = new Thread(new Consumer(buf));
  16.  
  17. cons.run();
  18. prod.run();
  19.  
  20. }
  21.  
  22. private class Consumer implements Runnable {
  23. private DummyBuffer<String> buf;
  24.  
  25. public Consumer(DummyBuffer<String> buf) {
  26. this.buf = buf;
  27. }
  28.  
  29. @Override
  30. public void run() {
  31. buf.take();
  32. }
  33. }
  34. private class Producer implements Runnable {
  35. private DummyBuffer<String> buf;
  36.  
  37. public Producer(DummyBuffer<String> buf) {
  38. this.buf = buf;
  39. }
  40.  
  41. @Override
  42. public void run() {
  43. System.out.println("Producer there...");
  44. buf.put("Hello World!");
  45. }
  46. }
  47.  
  48. private class DummyBuffer<T> {
  49. private final int SIZE;
  50. private List<T> data;
  51.  
  52. public DummyBuffer(List<T> sharedData, int maxSize) {
  53. SIZE = maxSize;
  54. data = sharedData;
  55. }
  56.  
  57. public synchronized T take() {
  58. while (data.isEmpty()) {
  59. try {
  60. System.out.println("waiting... for taking");
  61. wait();
  62. }
  63. // Do nothing
  64. }
  65. }
  66. T item = data.remove(data.size() - 1);
  67.  
  68. notifyAll();
  69.  
  70. System.out.println("Removed item: " + item);
  71. return item;
  72. }
  73.  
  74. public synchronized void put(T item) {
  75. while (data.size() >= SIZE) {
  76. try {
  77. wait();
  78. }
  79. // Do nothing
  80. }
  81. }
  82. data.add(item);
  83.  
  84. System.out.println("notified");
  85. notifyAll();
  86.  
  87. System.out.println("Put item: " + item);
  88. }
  89. }
  90. }
Time limit exceeded #stdin #stdout 5s 380224KB
stdin
Standard input is empty
stdout
waiting... for taking