join方法实现顺序打印ABC

顺序实现打印ABC可以用如下方法实现:

public class SequentialPrintABC {
    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(() -> System.out.print("A"));
        Thread threadB = new Thread(() -> {
            try {
                threadA.join(); // 等待A线程完成
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.print("B");
        });
        Thread threadC = new Thread(() -> {
            try {
                threadB.join(); // 等待B线程完成
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.print("C");
        });

        threadA.start();
        threadB.start();
        threadC.start();

        // 确保主线程等待所有线程完成
        threadC.join();
    }
}

你可能感兴趣的:(java,intellij-idea,android)