Implementation ideas: First, write a method for judging prime numbers.
public static boolean isPrime (int num) {
int sqrt = (int) Math.sqrt (num);
for (int i = 2 ; i <= sqrt ; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Then create two threads. I am using an anonymous inner class to create a subclass object, rewrite the run method, and let the run method execute the result of judging the prime number. If it is a prime number and print it out, define a sum to accumulate and record the prime numbers of 10-20. and. The same goes for the second thread.
/**
* Created with IntelliJ IDEA.
*
* @Author: 管坤坤
* @Date: 2021/12/06/8:53
* @Description:编写一个具有两个线程的程序,第一个线程求10~20之间的素数和它们的和,第二个线程求1000~2000之间的素数和它们的和。
*/
public class threadDemo12 extends Thread {
public static boolean isPrime (int num) {
int sqrt = (int) Math.sqrt (num);
for (int i = 2 ; i <= sqrt ; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main (String[] args) {
Thread t1 = new Thread () {
@Override
public void run () {
int sum = 0;
for (int k = 10 ; k <= 20 ; k++) {
if (isPrime (k)) {
sum += k;
System.out.print (k + " ");
}
}
System.out.println ("10-20的素数和"+sum);
}
};
Thread t2 = new Thread () {
@Override
public void run () {
int sum = 0;
for (int k = 1000 ; k <= 2000 ; k++) {
if (isPrime (k)) {
sum += k;
System.out.print (k + " ");
}
}
System.out.println ("1000-2000的素数和"+sum);
}
};
t1.start ();
t2.start ();
}
}
执行结果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/c5db351e820e46708bf03eebdb48489a.png)