可以使用Java中的Thread类来创建线程,并通过Runnable接口实现多线程打印随机数的功能。以下是一个示例代码:

import java.util.Random;

public class RandomNumberPrinter implements Runnable {
    private String threadName;
    private static final int MAX_NUMBER = 100;

    public RandomNumberPrinter(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        Random random = new Random();
        for (int i = 0; i <= MAX_NUMBER; i++) {
            int randomNumber = random.nextInt(MAX_NUMBER + 1);
            System.out.println(threadName + ": " + randomNumber);
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new RandomNumberPrinter("Thread 1"));
        Thread thread2 = new Thread(new RandomNumberPrinter("Thread 2"));
        Thread thread3 = new Thread(new RandomNumberPrinter("Thread 3"));

        thread1.start();
        thread2.start();
        thread3.start();
    }
}

在上述代码中,首先创建了一个RandomNumberPrinter类,实现了Runnable接口,并在run()方法中使用Random类生成0-100的随机数,并打印线程名和随机数。

在main()方法中,创建了三个Thread对象,并分别传入不同的RandomNumberPrinter实例作为参数。然后使用start()方法启动线程。

当运行该代码时,三个线程会同时执行,并在控制台上输出线程名和对应的随机数

java创建三个线程同时在打印台上打印0-100随机数附上线程名

原文地址: https://www.cveoy.top/t/topic/hJ2a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录