启动三个线程:AA、BB、CC

    • AA打印5次,BB打印5次,CC打印5次
    • 重复10轮

    解决方案:指定标识
    image.png

    1. class ThreadResource{
    2. private int flag=1;//AA:1 BB:2 CC:3
    3. private Lock lock=new ReentrantLock();
    4. //为什么要创建三个condition?上一个例子是创建一个condition,唤醒所有的线程
    5. //这里创建三个condition,通知下一个要执行的线程的condition
    6. private Condition c1=lock.newCondition();
    7. private Condition c2=lock.newCondition();
    8. private Condition c3=lock.newCondition();
    9. public void print5(int loop) throws InterruptedException {
    10. //上锁
    11. lock.lock();
    12. try {
    13. while(flag!=1){
    14. c1.await();//等待
    15. }
    16. for(int i=1;i<=5;i++){
    17. System.out.println(Thread.currentThread().getName()+"::"+i+"第"+loop+"轮");
    18. }
    19. flag=2;//修改标志位
    20. c2.signal();//通知BB线程
    21. }finally {
    22. lock.unlock();
    23. }
    24. }
    25. public void print10(int loop) throws InterruptedException {
    26. //上锁
    27. lock.lock();
    28. try {
    29. while(flag!=2){
    30. c2.await();//等待
    31. }
    32. for(int i=1;i<=10;i++){
    33. System.out.println(Thread.currentThread().getName()+"::"+i+"第"+loop+"轮");
    34. }
    35. flag=3;//修改标志位
    36. c3.signal();//通知CC线程
    37. }finally {
    38. lock.unlock();
    39. }
    40. }
    41. public void print15(int loop) throws InterruptedException {
    42. //上锁
    43. lock.lock();
    44. try {
    45. while(flag!=3){
    46. c3.await();//等待
    47. }
    48. for(int i=1;i<=15;i++){
    49. System.out.println(Thread.currentThread().getName()+"::"+i+"第"+loop+"轮");
    50. }
    51. flag=1;//修改标志位
    52. c1.signal();//通知BB线程
    53. }finally {
    54. lock.unlock();
    55. }
    56. }
    57. }
    58. public class ThreadDemo {
    59. public static void main(String[] args) {
    60. ThreadResource threadResource = new ThreadResource();
    61. new Thread(()->{
    62. for(int i=1;i<=10;i++){
    63. try {
    64. threadResource.print5(i);
    65. } catch (InterruptedException e) {
    66. e.printStackTrace();
    67. }
    68. }
    69. },"AA").start();
    70. new Thread(()->{
    71. for(int i=1;i<=10;i++){
    72. try {
    73. threadResource.print10(i);
    74. } catch (InterruptedException e) {
    75. e.printStackTrace();
    76. }
    77. }
    78. },"BB").start();
    79. new Thread(()->{
    80. for(int i=1;i<=10;i++){
    81. try {
    82. threadResource.print15(i);
    83. } catch (InterruptedException e) {
    84. e.printStackTrace();
    85. }
    86. }
    87. },"CC").start();
    88. }
    89. }