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


【Java|Java 三个线程依次输出ABC】转载于:https://www.cnblogs.com/lvjianwei/p/10578845.html

    推荐阅读