fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. MySemaphore mySemaphore = new MySemaphore();
  6. new Send(mySemaphore).start();
  7. new Receive(mySemaphore).start();
  8. }
  9. }
  10.  
  11. class MySemaphore {
  12. boolean flag = false;
  13.  
  14. public synchronized void take() throws InterruptedException {
  15. flag = true;
  16. notify();
  17. }
  18.  
  19. public synchronized void release() throws InterruptedException {
  20. while (!flag) {
  21. wait();
  22. }
  23. flag = false;
  24. }
  25. }
  26.  
  27. class Send extends Thread {
  28. MySemaphore mySemaphore;
  29.  
  30. public Send(MySemaphore semaphore) {
  31. this.mySemaphore = semaphore;
  32. }
  33.  
  34. @Override
  35. public void run() {
  36. int i = 0;
  37. while (i++ < 10) {
  38. System.out.println("send");
  39. try {
  40. mySemaphore.take();
  41. } catch (InterruptedException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
  46. }
  47.  
  48. class Receive extends Thread {
  49. MySemaphore mySemaphore;
  50.  
  51. public Receive(MySemaphore semaphore) {
  52. this.mySemaphore = semaphore;
  53. }
  54.  
  55. @Override
  56. public void run() {
  57. while (true) {
  58. try {
  59. mySemaphore.release();
  60. } catch (InterruptedException e) {
  61. e.printStackTrace();
  62. }
  63. System.out.println("receive");
  64. }
  65. }
  66. }
Time limit exceeded #stdin #stdout 5s 380864KB
stdin
Standard input is empty
stdout
send
send
send
send
send
send
send
send
send
send
receive