编写一个有两个线程的程序,第一个线程用来计算2到100之间的素数的个数,第二个线程用来计算100到200之间素数的个数,最后输出结果。编写Java程序
时间: 2024-03-09 22:47:53 浏览: 16
以下是Java程序代码:
```
public class PrimeThread extends Thread {
private int startNum;
private int endNum;
private int count;
public PrimeThread(int startNum, int endNum) {
this.startNum = startNum;
this.endNum = endNum;
this.count = 0;
}
public int getCount() {
return count;
}
public void run() {
for (int i = startNum; i <= endNum; i++) {
if (isPrime(i)) {
count++;
}
}
}
private boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
public class Main {
public static void main(String[] args) {
PrimeThread thread1 = new PrimeThread(2, 100);
PrimeThread thread2 = new PrimeThread(100, 200);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
int total = thread1.getCount() + thread2.getCount();
System.out.println("Total number of prime numbers between 2 and 200: " + total);
}
}
```
上述程序定义了一个 PrimeThread 类,用于计算一个区间内的素数个数。在 Main 类中创建了两个 PrimeThread 实例,并分别计算 2 到 100,和 100 到 200 之间的素数个数。最后将两个线程计算出的素数个数相加,输出总数。
程序运行结果如下:
```
Total number of prime numbers between 2 and 200: 46
```