一道算法题,N个线程,顺序打印M个数字(踩坑点) – billy wan‘s blogs

题目:

  • N个线程,顺序打印M个数字

  • 例如:4个线程,14个数字。

    效果:
    Thread-0-0
    Thread-1-1
    Thread-2-2
    Thread-3-3
    Thread-0-4
    Thread-1-5
    Thread-2-6
    Thread-3-7
    Thread-0-8
    Thread-1-9
    Thread-2-10
    Thread-3-11
    Thread-0-12
    Thread-1-13

  • 代码段:

    
    import java.util.*;
    import java.util.concurrent.Semaphore;
    public class Main {
    //结果值
    public static volatile int r_num = 0;
    
    //线程数
    public static int t_num = 0;
    
    //需要打印的数值
    public static int print_num = 0;
    
    //信号量为1,严格限制只有1个线程输出
    public static final Semaphore sem = new Semaphore(1);
    
    public static void main(String[] args) {
        //1.读取输入行数据
        Scanner scan = new Scanner(System.in);
    
        //t_num:创建的线程数
        t_num = 4; // =scan.nextInt();
        //print_num:需要打印出来的数字
        print_num = 14; // =scan.nextInt();
    
        //2.创建指定的线程数
        for (int i = 0; i < t_num; i++) {
            Thread t = new Thread(new Task(i));
            t.setName("Thread-" + i);
            t.start();
        }
    }
    
    /**
    @desc 打印数字
    @param num2 需要打印出来的数字
    **/
    static class Task implements Runnable {
        //线程绑定的序号
        private int t_index;
    
        public Task(int t_index) {
            this.t_index = t_index;
        }
    
        public void run() {
            while (r_num < print_num) {
                //注意,这里有坑,如果当2个线程r_num刚好到了临界点print_num之后
                //if条件还需要再次判断r_num < print_num,
                //要不然输出的时候会得不到想要的结果
                if (((r_num % t_num) == t_index) && (r_num < print_num)) {
                    try {
                        sem.acquire();
                        System.out.println(Thread.currentThread().getName() +
                            "-" + r_num);
                        r_num++;
                    } catch (Exception e) {
                        //
                    } finally {
                        sem.release();
                    }
                }
            }
        }
    }
    }
    

转载请标明:https://wp.me/paCouF-36

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值