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

• Code Snippet:

import java.util.*;
import java.util.concurrent.Semaphore;
public class Main {
The result value
public static volatile int r_num = 0;

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++) {
t.start();
}
}

/**
@desc 打印数字
@param num2 需要打印出来的数字
**/
static class Task implements Runnable {
//线程绑定的序号
private 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();
"-" + r_num);
r_num++;
} catch (Exception e) {
//
} finally {
sem.release();
}
}
}
}
}
}