一道算法题,N个线程,顺序打印M个数字(踩坑点)

1338人浏览 / 0人评论 / 添加收藏

     题目: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();
       }
   }
   /**
    * @param num2 需要打印出来的数字
    * @desc 打印数字
    **/
   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();
                   }
               }
           }
       }
   }
}

读后有收获可以扫码扫描公众号了解更多信息哟!

全部评论