线程通信方式:condition+lock实现线程之间的通信方式

小灰灰 2024-04-19 15:52 156阅读 0赞
  1. /*
  2. * 线程质之间的通信方式二:condition+lock实现线程之间的通信方式
  3. * */
  4. public class ThreadCommunication2 {
  5. private int i = 0;
  6. /*重入锁:参数: true 代表公平锁 ,false:独占锁*/
  7. private Lock lock = new ReentrantLock(false);
  8. private Condition condition = lock.newCondition();
  9. /*奇数*/
  10. public void odd() {
  11. while (i < 10) {
  12. try {
  13. lock.lock();
  14. if (i % 2 == 1) {
  15. /*唤醒该线程*/
  16. condition.signal();
  17. System.out.println("奇数:" + i+","+Thread.currentThread().getName());
  18. i++;
  19. } else {
  20. try {
  21. /*该线程等待*/
  22. condition.await();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. } finally {
  28. lock.unlock();
  29. }
  30. }
  31. }
  32. /*偶数*/
  33. public void even() {
  34. while (i < 10) {
  35. lock.lock();
  36. try {
  37. if (i % 2 == 0) {
  38. System.out.println("偶数:" + i +","+Thread.currentThread().getName());
  39. i++;
  40. /*唤醒该线程*/
  41. condition.signal();
  42. } else {
  43. try {
  44. /*该线程等待*/
  45. condition.await();
  46. } catch (InterruptedException e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. } finally {
  51. lock.unlock();
  52. }
  53. }
  54. }
  55. public static void main(String[] args) {
  56. ThreadCommunication2 threadCommunication = new ThreadCommunication2();
  57. Thread thread1 = new Thread("thread1") {
  58. @Override
  59. public void run() {
  60. threadCommunication.odd();
  61. }
  62. };
  63. Thread thread2 = new Thread("thread2") {
  64. @Override
  65. public void run() {
  66. threadCommunication.even();
  67. }
  68. };
  69. thread1.start();
  70. thread2.start();
  71. }
  72. }

运行结果:

  1. 偶数:0,thread2
  2. 奇数:1,thread1
  3. 偶数:2,thread2
  4. 奇数:3,thread1
  5. 偶数:4,thread2
  6. 奇数:5,thread1
  7. 偶数:6,thread2
  8. 奇数:7,thread1
  9. 偶数:8,thread2
  10. 奇数:9,thread1

发表评论

表情:
评论列表 (有 0 条评论,156人围观)

还没有评论,来说两句吧...

相关阅读