public class Main { public static boolean isPrime(int n) { if(n < 2) return false; if(n == 2) return true; if(n%2==0) return false; for(int i = 3; i < n; i += 2) if(n%i == 0) return false; return true; } public static void main(String[] args) throws InterruptedException { long time1 = System.currentTimeMillis(),time2; Task task1 = new Task(1,100000); Task task2 = new Task(100001,200000); Thread thread1 = new Thread(task1); Thread thread2 = new Thread(task2); thread1.start(); thread2.start(); while (thread1.isAlive() || thread2.isAlive()){ Thread.sleep(1); } time2 = System.currentTimeMillis(); System.out.println("总耗时:"+(time2 - time1)+"毫秒"); } } class Task implements Runnable{ private int start; private int end; Task(int start, int end) { this.start = start; this.end = end; } public void run() { long time = System.currentTimeMillis(); long count = 0; for(int i=start;i<=end;++i){ if(Main.isPrime(i)) count+=i; } System.out.println(String.format("%d-%d之间质数和为%d,耗时:%d毫秒",start,end,count,(System.currentTimeMillis()- time))); } }每句加注释
时间: 2024-03-10 13:49:48 浏览: 57
java代码-输入N,输出大于N的质数
这是一个Java程序,包含一个Main类和一个Task类,代码如下:
```java
public class Main {
// 判断一个数是否为质数
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i < n; i += 2)
if (n % i == 0) return false;
return true;
}
public static void main(String[] args) throws InterruptedException {
long time1 = System.currentTimeMillis(), time2;
// 创建两个任务,分别计算1-100000和100001-200000之间的质数和
Task task1 = new Task(1, 100000);
Task task2 = new Task(100001, 200000);
// 创建两个线程,分别执行两个任务
Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
// 启动线程
thread1.start();
thread2.start();
// 等待两个线程执行完毕
while (thread1.isAlive() || thread2.isAlive()) {
Thread.sleep(1);
}
time2 = System.currentTimeMillis();
System.out.println("总耗时:" + (time2 - time1) + "毫秒");
}
}
class Task implements Runnable {
private int start; // 起始数值
private int end; // 结束数值
Task(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
long time = System.currentTimeMillis();
long count = 0;
// 计算起始数值到结束数值之间的质数和
for (int i = start; i <= end; ++i) {
if (Main.isPrime(i)) count += i;
}
// 输出计算结果和耗时
System.out.println(String.format("%d-%d之间质数和为%d,耗时:%d毫秒", start, end, count, (System.currentTimeMillis() - time)));
}
}
```
其中,Main类的`isPrime`方法用于判断一个数是否为质数,采用了常见的质数判定算法;`main`方法创建了两个任务,分别计算1-100000和100001-200000之间的质数和,创建了两个线程分别执行这两个任务,等待线程执行完毕后输出总耗时;Task类实现了Runnable接口,用于执行具体的任务,其中的`run`方法计算起始数值到结束数值之间的质数和,输出计算结果和耗时。
阅读全文