Java 三個線程依次輸出ABC

源於:https://lax.v2ex.com/t/547045#reply43java

編寫一個程序,開啓 3 個線程 A,B,C,這三個線程的輸出分別爲 A、B、C,每一個線程將本身的 輸出在屏幕上打印 10 遍,要求輸出的結果必須按順序顯示。如:ABCABCABC....spa

 

 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 }
相關文章
相關標籤/搜索