比如三个线程分别打印 A,B,C,顺序执行5次,最后输出ABCABCABCABCABC
主要依赖线程的join方法
实现代码如下:
package com.cn.springboot.bootdemo.controller;import org.springframework.web.bind.annotation.RestController;@RestController
public class Demo2Controller {public static void main(String[] agrs) throws InterruptedException {for(int i = 0; i < 5; i++){printABC();}}public static void printABC() throws InterruptedException {Thread t1 = new Thread(() -> {System.out.print("A");});// 线程必须要先start,才能join,只有启动了,才能对线程进行操作t1.start();t1.join();Thread t2 = new Thread(() -> {System.out.print("B");});t2.start();t2.join();Thread t3 = new Thread(() -> {System.out.print("C");});t3.start();t3.join();}}