Java 三个线程依次输出ABC

源于:https://lax.v2ex.com/t/547045#reply43

编写一个程序,开启 3 个线程 A,B,C,这三个线程的输出分别为 A、B、C,每个线程将自己的 输出在屏幕上打印 10 遍,要求输出的结果必须按顺序显示。如:ABCABCABC....

 

 1 package com.ljw.HelloJava;
 2 
 3 import java.util.concurrent.TimeUnit;
 4 import java.util.function.Predicate;
 5 
 6 public class ABCThreads {
 7     private static Integer index = 0;
 8     private static Integer max = 6;
 9     private static Object lock = new Object();
10 
11     public static void main(String[] args) {
12 
13         Thread a = getThread(i -> i % 3 == 0, "A");
14         Thread b = getThread(i -> i % 3 == 1, "B");
15         Thread c = getThread(i -> i % 3 == 2, "C");
16         a.start();
17         b.start();
18         c.start();
19 
20     }
21 
22     private static Thread getThread(Predicate<Integer> condition, String value) {
23         return new Thread(() -> {
24             while (true) {
25                 synchronized (lock) {
26                     while (!condition.test(index)) {
27                         try {
28                             //如果已经不需要继续,直接return,避免继续等待
29                             if (index >= max) {
30                                 return;
31                             }
32                             lock.wait();
33                         } catch (InterruptedException e) {
34                             System.out.println(e.getMessage());
35                         }
36                     }
37                     //如果已经不需要继续,通知所有wait的线程收拾东西回家后,然后自己回家
38                     if (index >= max) {
39                         lock.notifyAll();
40                         return;
41                     }
42 
43                     System.out.printf("index:%s,value:%s\n", index, value);
44                     index++;
45                     lock.notifyAll();
46                 }
47             }
48         });
49     }
50 }

 

posted on 2019-03-22 15:57  Lv Jianwei  阅读(1893)  评论(0编辑  收藏  举报