读书人

java 并发之(一)同步器(synchroniz

发布时间: 2013-03-13 10:56:58 作者: rapoo

java 并发之(一)同步器(synchronizer)CountDownLatch、CyclicBarrier、Semaphore

      1. import?java.util.Collections;??
      2. import?java.util.HashSet;??
      3. import?java.util.Set;??
      4. import?java.util.concurrent.ExecutorService;??
      5. import?java.util.concurrent.Executors;??
      6. import?java.util.concurrent.Semaphore;??
      7. ??
      8. public?class?TestSemaphore?{??
      9. ??
      10. ????public?static?void?main(String[]?args)?{??
      11. ????????ExecutorService?exec?=?Executors.newCachedThreadPool();??
      12. ????????TestSemaphore?t?=?new?TestSemaphore();??
      13. ????????final?BoundedHashSet<String>?set?=?t.getSet();??
      14. ??
      15. ????????for?(int?i?=?0;?i?<?3;?i++)?{//三个线程同时操作add??
      16. ????????????exec.execute(new?Runnable()?{??
      17. ????????????????public?void?run()?{??
      18. ????????????????????try?{??
      19. ????????????????????????set.add(Thread.currentThread().getName());??
      20. ????????????????????}?catch?(InterruptedException?e)?{??
      21. ????????????????????????e.printStackTrace();??
      22. ????????????????????}??
      23. ????????????????}??
      24. ????????????});??
      25. ????????}??
      26. ??
      27. ????????for?(int?j?=?0;?j?<?3;?j++)?{//三个线程同时操作remove??
      28. ????????????exec.execute(new?Runnable()?{??
      29. ????????????????public?void?run()?{??
      30. ????????????????????set.remove(Thread.currentThread().getName());??
      31. ????????????????}??
      32. ????????????});??
      33. ????????}??
      34. ????????exec.shutdown();??
      35. ????}??
      36. ??
      37. ????public?BoundedHashSet<String>?getSet()?{??
      38. ????????return?new?BoundedHashSet<String>(2);//定义一个边界约束为2的线程??
      39. ????}??
      40. ??
      41. ????class?BoundedHashSet<T>?{??
      42. ????????private?final?Set<T>?set;??
      43. ????????private?final?Semaphore?semaphore;??
      44. ??
      45. ????????public?BoundedHashSet(int?bound)?{??
      46. ????????????this.set?=?Collections.synchronizedSet(new?HashSet<T>());??
      47. ????????????this.semaphore?=?new?Semaphore(bound,?true);??
      48. ????????}??
      49. ??
      50. ????????public?void?add(T?o)?throws?InterruptedException?{??
      51. ????????????semaphore.acquire();//信号量控制可访问的线程数目??
      52. ????????????set.add(o);??
      53. ????????????System.out.printf("add:%s%n",o);??
      54. ????????}??
      55. ??
      56. ????????public?void?remove(T?o)?{??
      57. ????????????if?(set.remove(o))??
      58. ????????????????semaphore.release();//释放掉信号量??
      59. ????????????System.out.printf("remove:%s%n",o);??
      60. ????????}??
      61. ????}??
      62. }??



      ??? 总结:Semaphore通常用于对象池的控制?(使用其对HTTP线程池的线程数进行控制)

      ?

      ?

读书人网 >编程

热点推荐