当前位置: 代码迷 >> 综合 >> 多线程打印从1到n的序列
  详细解决方案

多线程打印从1到n的序列

热度:30   发布时间:2024-02-06 19:02:39.0

要求

给定n,m。要求从打印从1到n 的数字,并用m个线程去打印,各个线程按顺序交替打印

1. 信号量实现方案

public class MultiThreadPrintNSemaphore {// 打印数字nprivate final int n;// 打印线程总数private final int threadCount;// 信号量private Semaphore[] semaphores;public MultiThreadPrintNSemaphore(int n, int threadCount) {this.n = n;this.threadCount = threadCount;this.semaphores = new Semaphore[n];for (int i = 0; i < this.threadCount; ++i) {semaphores[i] = new Semaphore(0);}semaphores[0].release();}public void print() {for (int i = 0; i < threadCount; ++i) {new MyThead(i + 1, n, threadCount, semaphores[i], semaphores[(i + 1) % threadCount]).start();}}static class MyThead extends Thread {// 线程序号private final int num;private final int n;private final int threadCount;private Semaphore currentSemaphore;private Semaphore nextSemaphore;public MyThead(int num, int n, int threadCount, Semaphore currentSemaphore, Semaphore nextSemaphore) {this.num = num;this.n = n;this.threadCount = threadCount;this.currentSemaphore = currentSemaphore;this.nextSemaphore = nextSemaphore;}@SneakyThrows@Overridepublic void run() {for (int i = num; i <= n; i += threadCount) {currentSemaphore.acquire();System.out.println("线程序号" + num + ":" + i);nextSemaphore.release();}}}public static void main(String[] args) {new MultiThreadPrintNSemaphore(10, 4).print();}
}

结果

线程序号1:1
线程序号2:2
线程序号3:3
线程序号4:4
线程序号1:5
线程序号2:6
线程序号3:7
线程序号4:8
线程序号1:9
线程序号2:10

 

  相关解决方案