Guest User

Untitled

a guest
Oct 22nd, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. import java.util.concurrent.TimeUnit;
  2. import java.util.*;
  3. import java.util.concurrent.*;
  4.  
  5. public class Hotel
  6. {
  7. private boolean taken = false;
  8. public synchronized
  9. void take() throws InterruptedException
  10. {
  11. while(taken)
  12. wait();
  13. taken = true;
  14. }
  15. public synchronized void free()
  16. {
  17. taken = false;
  18. notifyAll();
  19. }
  20. }
  21. class Client implements Runnable
  22. {
  23. private Hotel room;
  24. private final int id;
  25. private final int live;
  26. private Random rand = new Random(50);
  27. private void pause() throws InterruptedException
  28. {
  29. if(live==0) return;
  30. TimeUnit.MILLISECONDS.sleep(rand.nextInt(live*250));
  31. }
  32. public Client(Hotel room, int ident, int l)
  33. {
  34. this.room = room;
  35. id = ident;
  36. live = l;
  37. }
  38. public void run()
  39. {
  40. try
  41. {
  42. while(!Thread.interrupted())
  43. {
  44. System.out.println(this+" "+"freed");
  45. pause();
  46. System.out.println(this+" "+"settled");
  47. room.take();
  48. System.out.println(this+" "+"live");
  49. pause();
  50. room.free();
  51. }
  52. }
  53. catch(InterruptedException e)
  54. {
  55. System.out.println(this+" "+"exiting via interrupt");
  56. }
  57. }
  58. public String toString()
  59. {
  60. return "Client"+id;
  61. }
  62. }
  63. class Test
  64. {
  65. public static void main(String[] args)
  66. {
  67. Hotel h = new Hotel();
  68. for(int i=0; i<=50; i++)
  69. {
  70. Thread t = new Thread(new Client(h, i, 10));
  71. t.start();
  72. }
  73. }
  74. }
Add Comment
Please, Sign In to add comment