题目:
-
例如: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