java创建三个线程同时在打印台上打印0-100随机数
下面是使用Java编写的示例代码,创建三个线程,同时在控制台上打印0-100的随机数。
import java.util.Random;
public class RandomNumberPrinter implements Runnable {
@Override
public void run() {
Random random = new Random();
for (int i = 0; i <= 100; i++) {
int randomNumber = random.nextInt(101);
System.out.println(Thread.currentThread().getName() + ": " + randomNumber);
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new RandomNumberPrinter());
Thread thread2 = new Thread(new RandomNumberPrinter());
Thread thread3 = new Thread(new RandomNumberPrinter());
thread1.start();
thread2.start();
thread3.start();
}
}
运行以上代码,会创建三个线程,每个线程都会打印0-100之间的随机数。输出结果类似于:
Thread-0: 45
Thread-1: 67
Thread-2: 12
Thread-0: 78
Thread-1: 89
Thread-2: 34
...
请注意,由于多线程的执行是异步的,所以输出结果的顺序可能会不同
原文地址: https://www.cveoy.top/t/topic/hJ1h 著作权归作者所有。请勿转载和采集!