Java NIO - Condition

来源:互联网 发布:淘宝推广怎么做 编辑:程序博客网 时间:2024/06/08 17:58

Condition用来实现对应Object的wati,notify,notifyAll三个方法。

在Condition中用await()替换wait(),用signal()替换notify() ,用signalAll()替换notifyAll(),传统线程之间的通讯Condition都可以实现。如下列子,我们实现一个读写操作,分为读写线程。

  1. package chp3.condition;
  2. import java.util.concurrent.locks.Condition;
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5. public class BufferThread {
  6. final Lock lock = new ReentrantLock();// 锁
  7. final Condition notFull = lock.newCondition();// 写线程条件
  8. final Condition notEmpty = lock.newCondition();// 读线程条件
  9. final Object[] items = new Object[10];// 缓存队列
  10. int putptr/* 写索引 */, takeptr/* 读索引 */, count/* 队列中存在的数据个数 */;
  11. public void put(Object x) throws InterruptedException {
  12. lock.lock();
  13. try {
  14. while (count == items.length) {
  15. notFull.await();// 阻塞写线程
  16. }
  17. System.out.println("写入操作: index =  " + putptr + " value = " + x);
  18. items[putptr++] = x;
  19. if (putptr == items.length)
  20. putptr = 0;// 如果写索引写到队列的最后一个位置了,那么置为0
  21. ++count;// 个数++
  22. notEmpty.signal();// 唤醒读线程
  23. } finally {
  24. lock.unlock();
  25. }
  26. }
  27. public Object take() throws InterruptedException {
  28. lock.lock();
  29. try {
  30. while (count == 0)
  31. // 如果队列为空
  32. notEmpty.await();// 阻塞读线程
  33. Object x = items[takeptr];// 取值
  34. System.out.println("读取操作: index =" + takeptr + " vale = " + x);
  35. if (++takeptr == items.length)
  36. takeptr = 0;// 如果读索引读到队列的最后一个位置了,那么置为0
  37. --count;// 个数--
  38. notFull.signal();// 唤醒写线程
  39. return x;
  40. } finally {
  41. lock.unlock();
  42. }
  43. }
  44. public static void main(String[] args) {
  45. final BufferThread bt = new BufferThread();
  46. Thread t1 = new Thread(new Runnable() {
  47. @Override
  48. public void run() {
  49. for (int i = 0; i < 250; i++)
  50. try {
  51. bt.put(i);
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. });
  57. Thread t2 = new Thread(new Runnable() {
  58. @Override
  59. public void run() {
  60. for (int i = 0; i < 230; i++)
  61. try {
  62. bt.take();
  63. } catch (InterruptedException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. });
  68. t1.start();
  69. t2.start();
  70. }
  71. }


参考:http://blog.csdn.net/ghsau/article/details/7481142

0 0
原创粉丝点击