多线程按顺序打印数字,支持配置线程数目和打印数字结尾

Posted zerodslearnjava

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程按顺序打印数字,支持配置线程数目和打印数字结尾相关的知识,希望对你有一定的参考价值。

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zerodsLyn
 * created on 2020/5/10
 */
public class MultiThreadSerialPrint {
    private final Thread[] threads;
    /**
     * 打印线程数目
     */
    final int threadNum;

    AtomicInteger num;

    private final int end;
    /**
       * 打印任务是否结束
       */
    volatile boolean running = true;

    public ThreadPrint(int threadNum, int end) {
        this.num = new AtomicInteger(0);
        this.end = end;
        this.threadNum = threadNum;
        this.threads = new Thread[threadNum];
        for (int i = 0; i < threadNum; i++) {
            Thread thread = new Thread(new PrintTask(this), "thread-" + i);
            threads[i] = thread;
        }
    }

    public void run() {
        for (Thread thread : threads) {
            thread.start();
        }
    }

    public static void main(String[] args) {
        ThreadPrint threadPrint = new ThreadPrint(10, 100);
        threadPrint.run();
        while (threadPrint.running) ;
        System.out.println("done");
    }

    private static class PrintTask implements Runnable {
        private final ThreadPrint threadPrint;
        public PrintTask(ThreadPrint threadPrint) {
            this.threadPrint = threadPrint;
        }

        @Override
        public void run() {
            while (threadPrint.running) {
                if (threadPrint.threads[threadPrint.num.get() % threadPrint.threadNum] == Thread.currentThread()) {
                    System.out.println(Thread.currentThread().getName() + " " + threadPrint.num.get());
                    if (threadPrint.num.get() == threadPrint.end) {
                        threadPrint.running = false;
                    }

                    threadPrint.num.incrementAndGet();
                }
            }
        }
    }
}

以上是关于多线程按顺序打印数字,支持配置线程数目和打印数字结尾的主要内容,如果未能解决你的问题,请参考以下文章

Java多个线程顺序打印数字

C/C++ - sem_t 类型的单个信号量按顺序打印数字

java多线程连续打印字母数字问题

多线程面试题之三线程按顺序交替打印ABC的方法

经典多线程问题-轮流打印字母和数字

java多线程轮流打印数字字母案例代码