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

本文介绍了如何使用信号量实现多线程环境下按顺序打印1到n的数字。针对给定的n和m,通过信号量控制m个线程交替执行,确保打印序列的正确性。
摘要由CSDN通过智能技术生成

要求

给定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;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值