A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. import java.util.concurrent.locks.*;
  2. class BoundedBuffer
  3. {
  4. final Lock lock = new ReentrantLock();
  5. final Condition notFull = lock.newCondition();
  6. final Condition notEmpty = lock.newCondition();

  7. final Object[] items = new Object[100];
  8. int count,putptr,takeptr;

  9. public void put(Object x)throws InterruptedException
  10. {
  11. lock.lock();
  12. try
  13. {
  14. while(count==items.length)
  15. notFull.await();
  16. items[putptr] = x;
  17. System.out.println(Thread.currentThread().getName()+"在向数组中添加第"+putptr+"号角标的元素:"+x);
  18. if(++putptr == items.length)
  19. putptr = 0;
  20. ++count;
  21. notEmpty.signal();
  22. }
  23. finally
  24. {
  25. lock.unlock();
  26. }
  27. }
  28. public Object take()throws InterruptedException
  29. {
  30. lock.lock();
  31. try
  32. {
  33. while(count==0)
  34. notEmpty.await();
  35. Object x = items[takeptr];
  36. System.out.println(Thread.currentThread().getName()+"在从数组中取出第"+takeptr+"号角标的元素:"+x);
  37. if(++takeptr == items.length)
  38. takeptr = 0;
  39. --count;
  40. notFull.signal();
  41. return x;
  42. }
  43. finally
  44. {
  45. lock.unlock();
  46. }
  47. }
  48. }
  49. class Put implements Runnable
  50. {
  51. BoundedBuffer bb;
  52. int x = 20;
  53. Put(BoundedBuffer bb)
  54. {
  55. this.bb = bb;
  56. }
  57. public void run()//不能抛,只能在内部进行try
  58. {
  59. while(x-->0)
  60. {
  61. try
  62. {
  63. bb.put(x);
  64. }
  65. catch (InterruptedException e)
  66. {
  67. }
  68. }
  69. }
  70. }
  71. class Take implements Runnable
  72. {
  73. BoundedBuffer bb;
  74. int x = 20;
  75. Take(BoundedBuffer bb)
  76. {
  77. this.bb = bb;
  78. }
  79. public void run()//不能抛,只能在内部进行try
  80. {
  81. while(x-->0)
  82. {
  83. try
  84. {
  85. System.out.println(bb.take());
  86. }
  87. catch (InterruptedException e)
  88. {
  89. }
  90. }
  91. }
  92. }
  93. class demo
  94. {
  95. public static void main(String[] s)
  96. {
  97. BoundedBuffer bb = new BoundedBuffer();
  98. Put p = new Put(bb);
  99. Take t = new Take(bb);
  100. new Thread(p).start();
  101. new Thread(p).start();
  102. new Thread(p).start();
  103. new Thread(p).start();

  104. new Thread(t).start();
  105. new Thread(t).start();
  106. new Thread(t).start();
  107. }
  108. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马