/** * 四个线程ABCD,分别打印A/B/C/D */ public class ABCD { public static void main(String[] args) { new PrintABCD().start(); } } class PrintABCD { private static enum PrintStatus { A, B, C, D }; private static PrintStatus nstatus; public void start() { nstatus = PrintStatus.A; Thread thread1 = new Thread(new PrintA()); Thread thread2 = new Thread(new PrintB()); Thread thread3 = new Thread(new PrintC()); Thread thread4 = new Thread(new PrintD()); thread1.start(); thread2.start(); thread3.start(); thread4.start(); } private synchronized void print(PrintStatus status) { if (nstatus == status) { // System.out.println(Thread.currentThread().getName() + " "); System.out.print(status); if (status == PrintStatus.D) { System.out.println(); } changeStatus(); return; } } private void chan
四个线程分别依次打印A/B/C/D,每个线程打印一个字母
这是一个Java程序,通过多线程实现四个线程PrintA、PrintB、PrintC和PrintD依次打印字母A、B、C和D。程序使用枚举类型PrintStatus跟踪当前应打印的字符,并利用synchronized关键字保证打印的顺序。每个线程在一个无限循环中调用print方法尝试打印其对应的字符,并在打印完D后换行。
摘要由CSDN通过智能技术生成