逻辑:当线程1 执行完之后 通知线程2 再通知3 循序
    用了ReentrantLock锁来完成,创建多个Condition

    1. package com.daijunyi.lock;
    2. import java.util.concurrent.locks.Condition;
    3. import java.util.concurrent.locks.ReentrantLock;
    4. public class PrintTest {
    5. private int flag = 0; //0表示 c1 1表示 c2 2表示c3
    6. private ReentrantLock reentrantLock = new ReentrantLock();
    7. private Condition c1 = reentrantLock.newCondition();
    8. private Condition c2 = reentrantLock.newCondition();
    9. private Condition c3 = reentrantLock.newCondition();
    10. private void print1() throws InterruptedException {
    11. reentrantLock.lock();
    12. try {
    13. while (flag != 0){
    14. c1.await();
    15. }
    16. System.out.println(Thread.currentThread().getName()+"print1打印");
    17. flag = 1;
    18. c2.signal();
    19. }finally {
    20. reentrantLock.unlock();
    21. }
    22. }
    23. private void print2() throws InterruptedException {
    24. reentrantLock.lock();
    25. try {
    26. while (flag != 1){
    27. c2.await();
    28. }
    29. System.out.println(Thread.currentThread().getName()+"print2打印");
    30. flag = 2;
    31. c3.signal();
    32. }finally {
    33. reentrantLock.unlock();
    34. }
    35. }
    36. private void print3() throws InterruptedException {
    37. reentrantLock.lock();
    38. try {
    39. while (flag != 2){
    40. c3.await();
    41. }
    42. System.out.println(Thread.currentThread().getName()+"print3打印");
    43. flag = 0;
    44. c1.signal();
    45. }finally {
    46. reentrantLock.unlock();
    47. }
    48. }
    49. public static void main(String[] args) {
    50. PrintTest printTest = new PrintTest();
    51. new Thread(()->{
    52. for (int i=0;i<10;i++){
    53. try {
    54. printTest.print1();
    55. } catch (InterruptedException e) {
    56. e.printStackTrace();
    57. }
    58. }
    59. },"线程1").start();
    60. new Thread(()->{
    61. for (int i=0;i<10;i++) {
    62. try {
    63. printTest.print2();
    64. } catch (InterruptedException e) {
    65. e.printStackTrace();
    66. }
    67. }
    68. },"线程2").start();
    69. new Thread(()->{
    70. for (int i=0;i<10;i++) {
    71. try {
    72. printTest.print3();
    73. } catch (InterruptedException e) {
    74. e.printStackTrace();
    75. }
    76. }
    77. },"线程3").start();
    78. }
    79. }