Andorid之用ConditionVariable实现线程同步

举报
chenyu 发表于 2021/07/27 00:41:41 2021/07/27
【摘要】 一、学习ConditionVariable之前的复习 如果你不懂wait()、notify()怎么使用,最好先复习下我之前的这篇博客,怎么使用wait()、notify()实现生产者和消费者的关系   java之wait()、notify()实现非阻塞的生产者和消费者           二、看下...

一、学习ConditionVariable之前的复习

如果你不懂wait()、notify()怎么使用,最好先复习下我之前的这篇博客,怎么使用wait()、notify()实现生产者和消费者的关系

 

java之wait()、notify()实现非阻塞的生产者和消费者

 

 

 

 

 

二、看下ConditionVariable源代码实现


  
  1. package android.os;
  2. /**
  3. * Class that implements the condition variable locking paradigm.
  4. *
  5. * <p>
  6. * This differs from the built-in java.lang.Object wait() and notify()
  7. * in that this class contains the condition to wait on itself. That means
  8. * open(), close() and block() are sticky. If open() is called before block(),
  9. * block() will not block, and instead return immediately.
  10. *
  11. * <p>
  12. * This class uses itself as the object to wait on, so if you wait()
  13. * or notify() on a ConditionVariable, the results are undefined.
  14. */
  15. public class ConditionVariable
  16. {
  17. private volatile boolean mCondition;
  18. /**
  19. * Create the ConditionVariable in the default closed state.
  20. */
  21. public ConditionVariable()
  22. {
  23. mCondition = false;
  24. }
  25. /**
  26. * Create the ConditionVariable with the given state.
  27. *
  28. * <p>
  29. * Pass true for opened and false for closed.
  30. */
  31. public ConditionVariable(boolean state)
  32. {
  33. mCondition = state;
  34. }
  35. /**
  36. * Open the condition, and release all threads that are blocked.
  37. *
  38. * <p>
  39. * Any threads that later approach block() will not block unless close()
  40. * is called.
  41. */
  42. public void open()
  43. {
  44. synchronized (this) {
  45. boolean old = mCondition;
  46. mCondition = true;
  47. if (!old) {
  48. this.notifyAll();
  49. }
  50. }
  51. }
  52. /**
  53. * Reset the condition to the closed state.
  54. *
  55. * <p>
  56. * Any threads that call block() will block until someone calls open.
  57. */
  58. public void close()
  59. {
  60. synchronized (this) {
  61. mCondition = false;
  62. }
  63. }
  64. /**
  65. * Block the current thread until the condition is opened.
  66. *
  67. * <p>
  68. * If the condition is already opened, return immediately.
  69. */
  70. public void block()
  71. {
  72. synchronized (this) {
  73. while (!mCondition) {
  74. try {
  75. this.wait();
  76. }
  77. catch (InterruptedException e) {
  78. }
  79. }
  80. }
  81. }
  82. /**
  83. * Block the current thread until the condition is opened or until
  84. * timeout milliseconds have passed.
  85. *
  86. * <p>
  87. * If the condition is already opened, return immediately.
  88. *
  89. * @param timeout the maximum time to wait in milliseconds.
  90. *
  91. * @return true if the condition was opened, false if the call returns
  92. * because of the timeout.
  93. */
  94. public boolean block(long timeout)
  95. {
  96. // Object.wait(0) means wait forever, to mimic this, we just
  97. // call the other block() method in that case. It simplifies
  98. // this code for the common case.
  99. if (timeout != 0) {
  100. synchronized (this) {
  101. long now = System.currentTimeMillis();
  102. long end = now + timeout;
  103. while (!mCondition && now < end) {
  104. try {
  105. this.wait(end-now);
  106. }
  107. catch (InterruptedException e) {
  108. }
  109. now = System.currentTimeMillis();
  110. }
  111. return mCondition;
  112. }
  113. } else {
  114. this.block();
  115. return true;
  116. }
  117. }
  118. }

 

 

 

 

 

三、我们分析怎么使用

  比如有多个线程需要执行同样的代码的时候,我们一般希望当一个线程执行到这里之后,后面的线程在后面排队,然后等之前的线程执行完了再让这个线程执行,我们一般用synchronized实现,但是这里我们也可以用ConditionVariable实现,从源码可以看到,我们初始化可以传递一个boolean类型的参数进去,我们可以传递true进去


  
  1. public ConditionVariable(boolean state)
  2. {
  3. mCondition = state;
  4. }

然后你看下ConditionVariable类里面这个方法


  
  1. public void block()
  2. {
  3. synchronized (this) {
  4. while (!mCondition) {
  5. try {
  6. this.wait();
  7. }
  8. catch (InterruptedException e) {
  9. }
  10. }
  11. }
  12. }

如果第一次初始化的时候mCondition是true,那么第一次调用这里就不会走到wait函数,然后我们应该需要一个开关让mCondition变成false,让第二个线程进来的时候我们应该让线程执行wait()方法,阻塞在这里,这不看下ConditionVariable类里面这个函数


  
  1. public void close()
  2. {
  3. synchronized (this) {
  4. mCondition = false;
  5. }
  6. }

这不恰好是我们需要的,我们可以马上调用这个函数close(),然后让程序执行我们想执行的代码,最后要记得调用open方法,如下


  
  1. public void open()
  2. {
  3. synchronized (this) {
  4. boolean old = mCondition;
  5. mCondition = true;
  6. if (!old) {
  7. this.notifyAll();
  8. }
  9. }
  10. }

因为这里调用了notifyAll方法,把之前需要等待的线程呼唤醒

所以我们使用可以这样使用

1、初始化

ConditionVariable mLock = new ConditionVariable(true);
 

2、同步的地方这样使用


  
  1. mLock.block();
  2. mLock.close();
  3. /**
  4. 你的代码
  5. **/
  6. mLock.open();

 

 

 

 

四、测试代码分析

我先给出一个原始Demo

 


  
  1. public class MainActivity extends ActionBarActivity {
  2. public static final String TAG = "ConditionVariable_Test";
  3. @Override
  4. protected void onCreate(Bundle savedInstanceState) {
  5. super.onCreate(savedInstanceState);
  6. setContentView(R.layout.activity_main);
  7. for (int i = 0; i < 10; i++) {
  8. new Mythread("" + i).start();
  9. }
  10. }
  11. public int num = 5;
  12. class Mythread extends Thread {
  13. String name;
  14. public Mythread(String name) {
  15. this.name = name;
  16. }
  17. @Override
  18. public void run() {
  19. while (true) {
  20. try {
  21. Thread.sleep(1);
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. num--;
  26. if (num >= 0)
  27. Log.i(TAG, "thread name is:" + name + " num is:" + num);
  28. else
  29. break;
  30. }
  31. }
  32. }
  33. }

 

 

运行的结果是这样的:

 

 


  
  1. ConditionVariable_Test I thread name is:0 num is:4
  2. I thread name is:1 num is:3
  3. I thread name is:2 num is:2
  4. I thread name is:3 num is:1
  5. I thread name is:4 num is:0

很明显不是我们想要的结果,因为我想一个线程进来了,需要等到执行完了才让另外一个线程才能进来

 

我们用ConditionVariable来实现下


  
  1. package com.example.conditionvariable;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. import android.os.Bundle;
  5. import android.os.ConditionVariable;
  6. import android.support.v7.app.ActionBarActivity;
  7. import android.util.Log;
  8. public class MainActivity extends ActionBarActivity {
  9. public static final String TAG = "ConditionVariable_Test";
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. mCondition = new ConditionVariable(true);
  15. for (int i = 0; i < 10; i++) {
  16. new Mythread("" + i).start();
  17. }
  18. }
  19. public int num = 5;
  20. class Mythread extends Thread {
  21. String name;
  22. public Mythread(String name) {
  23. this.name = name;
  24. }
  25. @Override
  26. public void run() {
  27. mCondition.block();
  28. mCondition.close();
  29. while (true) {
  30. try {
  31. Thread.sleep(1);
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. num--;
  36. if (num >= 0)
  37. Log.i(TAG, "thread name is:" + name + " num is:" + num);
  38. else
  39. break;
  40. }
  41. mCondition.open();
  42. }
  43. }
  44. }

运行的结果如下


  
  1. onditionVariable_Test I thread name is:0 num is:4
  2. I thread name is:0 num is:3
  3. I thread name is:0 num is:2
  4. I thread name is:0 num is:1
  5. I thread name is:0 num is:0

很明显这是我想要的效果,还有其它办法吗?当然有

我们还可以使用ReentrantLock重入锁,代码修改如下


  
  1. public class MainActivity extends ActionBarActivity {
  2. public static final String TAG = "ConditionVariable_Test";
  3. private Lock lock = new ReentrantLock();
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_main);
  8. for (int i = 0; i < 10; i++) {
  9. new Mythread("" + i).start();
  10. }
  11. }
  12. public int num = 5;
  13. class Mythread extends Thread {
  14. String name;
  15. public Mythread(String name) {
  16. this.name = name;
  17. }
  18. @Override
  19. public void run() {
  20. lock.lock();
  21. while (true) {
  22. try {
  23. Thread.sleep(1);
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. num--;
  28. if (num >= 0)
  29. Log.i(TAG, "thread name is:" + name + " num is:" + num);
  30. else
  31. break;
  32. }
  33. lock.unlock();
  34. }
  35. }
  36. }

 

 

 

运行的结果如下


  
  1. onditionVariable_Test I thread name is:0 num is:4
  2. I thread name is:0 num is:3
  3. I thread name is:0 num is:2
  4. I thread name is:0 num is:1
  5. I thread name is:0 num is:0

很明显这是我想要的效果,还有其它办法吗?当然有,那就是用synchronized同步块,代码改成如下


  
  1. package com.example.conditionvariable;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. import android.os.Bundle;
  5. import android.os.ConditionVariable;
  6. import android.support.v7.app.ActionBarActivity;
  7. import android.util.Log;
  8. public class MainActivity extends ActionBarActivity {
  9. public static final String TAG = "ConditionVariable_Test";
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. for (int i = 0; i < 10; i++) {
  15. new Mythread("" + i).start();
  16. }
  17. }
  18. public int num = 5;
  19. class Mythread extends Thread {
  20. String name;
  21. public Mythread(String name) {
  22. this.name = name;
  23. }
  24. @Override
  25. public void run() {
  26. synchronized (MainActivity.class) {
  27. while (true) {
  28. try {
  29. Thread.sleep(1);
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. num--;
  34. if (num >= 0)
  35. Log.i(TAG, "thread name is:" + name + " num is:" + num);
  36. else
  37. break;
  38. }
  39. }
  40. }
  41. }
  42. }

运行的结果如下


  
  1. onditionVariable_Test I thread name is:0 num is:4
  2. I thread name is:0 num is:3
  3. I thread name is:0 num is:2
  4. I thread name is:0 num is:1
  5. I thread name is:0 num is:0

很明显这是我想要的效果

 

 

 

五、总结

在Android开发里面我们一般实现线程通过可以用ConditionVariableReentrantLock(重入锁)、synchronized阻塞队列(ArrayBlockingQueue、LinkedBlockingQueue)
   put(E e) : 在队尾添加一个元素,如果队列满则阻塞
   size() : 返回队列中的元素个数
   take() : 移除并返回队头元素,如果队列空则阻塞

 

 

 

 

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/80905528

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。