题目:两个线程交替输出1-100的数字,例如:t1--》1,t2--》2,....
题目:两个线程交替输出1-100的数字,例如:t1–》1,t2–》2,…
方法1:
要实现两个线程交替输出1到100的数字,可以使用信号量(Semaphore)来控制线程的执行顺序。每个线程在输出后释放对方的信号量,从而实现交替执行。
import java.util.concurrent.Semaphore;public class AlternatePrinting {private static int num = 1;private static final int MAX = 100;private static Semaphore s1 = new Semaphore(1); // 线程1先执行private static Semaphore s2 = new Semaphore(0); // 线程2等待public static void main(String[] args) {Thread t1 = new Thread(() -> {while (true) {try {s1.acquire(); // 获取s1许可if (num > MAX) {s2.release(); // 确保线程2能退出break;}System.out.println