用java分别实现以下两个程序(1) 写两个线程,一个线程打印1——52,另一个线程打印A——Z,打印顺序为:12A34B...5152Z (2) 编程实现三线程程序,其中一个线程计算1-1000的累加和,另一个线程求100!,在主线程输出1-1000的累加和与100!。
时间: 2024-05-13 12:16:33 浏览: 81
(1)
```java
public class PrintThread implements Runnable {
private int count = 1;
private char ch = 'A';
@Override
public void run() {
synchronized (this) {
while (count <= 52 && ch <= 'Z') {
if (count % 2 == 1) {
System.out.print(count++);
System.out.print(count++);
} else {
System.out.print(ch++);
}
}
}
}
}
public class Main {
public static void main(String[] args) {
PrintThread printThread = new PrintThread();
new Thread(printThread).start();
}
}
```
(2)
```java
public class SumThread implements Runnable {
private int sum = 0;
@Override
public void run() {
for (int i = 1; i <= 1000; i++) {
sum += i;
}
}
public int getSum() {
return sum;
}
}
public class FactorialThread implements Runnable {
private BigInteger factorial = BigInteger.ONE;
@Override
public void run() {
for (int i = 2; i <= 100; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
}
public BigInteger getFactorial() {
return factorial;
}
}
public class Main {
public static void main(String[] args) {
SumThread sumThread = new SumThread();
FactorialThread factorialThread = new FactorialThread();
Thread thread1 = new Thread(sumThread);
Thread thread2 = new Thread(factorialThread);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1-1000的累加和为:" + sumThread.getSum());
System.out.println("100!的值为:" + factorialThread.getFactorial());
}
}
```
阅读全文