Java 怎么实现每个线程打印“Hello from thread!”

2019年7月21日10:50:09 评论 82

1.简介

Java 怎么实现每个线程打印“Hello from thread<num>!”?——请看下文。

2.代码

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



public class Exercise4 implements Runnable {
    static int threadCount = 1;

    public static void main(String[] args) {
        reverseHello();
    }

    public static void reverseHello() {
        if (threadCount <= 10) {
            Thread thread = new Thread(new Exercise4());
            thread.start();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        threadCount++;
        reverseHello();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out
                .println("Hello from " + Thread.currentThread().getName());
    }

}

 

3.总结

示例代码演示了 Java 怎么实现每个线程打印“Hello from thread<num>!”,具体步骤参见示例代码。

发表评论

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