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

要求

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

1. 信号量实现方案

public class MultiThreadPrintNSemaphore {
    // 打印数字n
    private 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;
        }

        
        @Override
        public void run() {
            for (int i = num; i <= n; i += threadCount) {
                try {
                    currentSemaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                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

 

你可能感兴趣的:(java,juc)