在一个线程中求100以内素数,求出后休眠一个随机时间。在另一线程中求100以内能被3整除的数,求出后休眠一个随机时间。输出数据时应有提示,指明哪个线程输出的数据,java实现
时间: 2024-03-27 14:35:22 浏览: 43
好的,我来为你解答这个问题。以下是Java代码实现:
```java
import java.util.Random;
public class PrimeNumberThread extends Thread {
private final String threadName;
private final int maxNumber;
private final Random random;
public PrimeNumberThread(String threadName, int maxNumber) {
this.threadName = threadName;
this.maxNumber = maxNumber;
this.random = new Random();
}
@Override
public void run() {
System.out.println(threadName + " started.");
for (int i = 2; i <= maxNumber; i++) {
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(threadName + ": " + i);
try {
Thread.sleep(random.nextInt(3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(threadName + " finished.");
}
public static void main(String[] args) {
int maxNumber = 100;
PrimeNumberThread primeNumberThread = new PrimeNumberThread("PrimeNumberThread", maxNumber);
DivisibleByThreeThread divisibleByThreeThread = new DivisibleByThreeThread("DivisibleByThreeThread", maxNumber);
primeNumberThread.start();
divisibleByThreeThread.start();
}
}
class DivisibleByThreeThread extends Thread {
private final String threadName;
private final int maxNumber;
private final Random random;
public DivisibleByThreeThread(String threadName, int maxNumber) {
this.threadName = threadName;
this.maxNumber = maxNumber;
this.random = new Random();
}
@Override
public void run() {
System.out.println(threadName + " started.");
for (int i = 1; i <= maxNumber; i++) {
if (i % 3 == 0) {
System.out.println(threadName + ": " + i);
try {
Thread.sleep(random.nextInt(3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(threadName + " finished.");
}
}
```
代码中创建了两个线程,一个是求素数的线程,一个是求能被3整除的数的线程。在每个线程中,都使用了一个随机时间来模拟计算的耗时。在输出数据时,使用线程名来指明哪个线程输出的数据。最后,将两个线程都启动,程序就会开始执行。
阅读全文