other · 2022年1月23日 0

One algorithm problem, N threads, sequential printing of M numbers (stepping on the pit point)

topic:

  • N threads, print M numbers sequentially

  • For example: 4 threads, 14 numbers.

    effect:
    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

  • Code Snippet:

    import java.util.*;
    import java.util.concurrent.Semaphore;
    public class Main {
    The result value
    public static volatile int r_num = 0;
    
    The number of threads
    public static int t_num = 0;
    
    The numeric value that needs to be printed
    public static int print_num = 0;
    
    The semaphore is 1, and there is a strict limit to only 1 thread output
    public static final Semaphore sem = new Semaphore(1);
    
    public static void main(String [] args) {
        1. Read the input row data
        Scanner scan = new Scanner(System.in);
    
    t_num: The number of threads created
        t_num = 4; =scan.nextInt();
        print_num: Numbers that need to be printed
        print_num = 14; =scan.nextInt();
    
    2. Create the specified number of threads
        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();
                    }
                }
            }
        }
    }
    }

    Please indicate:https://wp.me/paCouF-36