Java 怎么实现一个程序由n个线程打印1到10组成

2019年7月21日10:50:26 评论 67

1.简介

Java 怎么实现一个程序由n个线程打印1到10组成?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

public class Main {
    static int threadCount = 5;

    public static void main(String[] args) {

        for (int i = 1; i <= threadCount; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    int thread = (int) Thread.currentThread().getId() - 10 + 1;
                    print(thread);
                }
            });
            thread.start();
        }
    }

    public static void print(int thread) {
        int temp = thread;
        int i = 1;
        while (temp <= 10) {
            System.out.println("Thread-" + thread + " : " + temp);
            temp = thread + threadCount * i++;
        }
    }
}

 

3.总结

示例代码演示了 Java 怎么实现一个程序由n个线程打印1到10组成,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: