2、(要交)用两种方式实现三个线程,第一个线程输出5遍1- 100,第二个线程输出5遍A-z,第三个线程找出2-100000之内的 素数并输出。java
时间: 2023-07-15 09:13:43 浏览: 86
用java程序找出素数
方式一:使用Thread类和Runnable接口实现三个线程。
```java
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintNumber());
Thread t2 = new Thread(new PrintLetter());
Thread t3 = new Thread(new FindPrime());
t1.start();
t2.start();
t3.start();
}
}
class PrintNumber implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
for (int j = 1; j <= 100; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
class PrintLetter implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
for (char j = 'A'; j <= 'Z'; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
class FindPrime implements Runnable {
private boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
@Override
public void run() {
for (int i = 2; i <= 100000; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}
```
方式二:使用继承Thread类实现三个线程。
```java
public class Main {
public static void main(String[] args) {
PrintNumber t1 = new PrintNumber();
PrintLetter t2 = new PrintLetter();
FindPrime t3 = new FindPrime();
t1.start();
t2.start();
t3.start();
}
}
class PrintNumber extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
for (int j = 1; j <= 100; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
class PrintLetter extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
for (char j = 'A'; j <= 'Z'; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
class FindPrime extends Thread {
private boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
@Override
public void run() {
for (int i = 2; i <= 100000; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
}
```
阅读全文