案例介绍

  • A 线程打印 5 次 A,B 线程打印 10 次 B,C 线程打印 15 次 C,按照 此顺序循环 10 轮

    1. public class ThreadDemo2 {
    2. private ReentrantLock reentrantLock = new ReentrantLock();
    3. private Condition c1 = reentrantLock.newCondition();
    4. private Condition c2 = reentrantLock.newCondition();
    5. private Condition c3 = reentrantLock.newCondition();
    6. private int flag = 1;
    7. private void printA() {
    8. reentrantLock.lock();
    9. try {
    10. while (flag != 1) {
    11. c1.await();
    12. }
    13. for (int i = 0; i < 5; i++) {
    14. System.out.print("A ");
    15. }
    16. System.out.println();
    17. flag = 2;
    18. c2.signal();
    19. } catch (Exception e) {
    20. e.printStackTrace();
    21. } finally {
    22. reentrantLock.unlock();
    23. }
    24. }
    25. private void printB() {
    26. reentrantLock.lock();
    27. try {
    28. while (flag != 2) {
    29. c2.await();
    30. }
    31. for (int i = 0; i < 10; i++) {
    32. System.out.print("B ");
    33. }
    34. System.out.println();
    35. flag = 3;
    36. c3.signal();
    37. } catch (Exception e) {
    38. e.printStackTrace();
    39. } finally {
    40. reentrantLock.unlock();
    41. }
    42. }
    43. private void printC() {
    44. reentrantLock.lock();
    45. try {
    46. while (flag != 3) {
    47. c3.await();
    48. }
    49. for (int i = 0; i < 15; i++) {
    50. System.out.print("C ");
    51. }
    52. System.out.println();
    53. flag = 1;
    54. c1.signal();
    55. } catch (Exception e) {
    56. e.printStackTrace();
    57. } finally {
    58. reentrantLock.unlock();
    59. }
    60. }
    61. public static void main(String[] args) {
    62. ThreadDemo2 demo2 = new ThreadDemo2();
    63. new Thread(() -> {
    64. for (int i = 0; i < 3; i++) {
    65. demo2.printA();
    66. }
    67. }).start();
    68. new Thread(() -> {
    69. for (int i = 0; i < 3; i++) {
    70. demo2.printB();
    71. }
    72. }).start();
    73. new Thread(() -> {
    74. for (int i = 0; i < 3; i++) {
    75. demo2.printC();
    76. }
    77. }).start();
    78. }
    79. }
  • image.png