编写Java程序:创建10个线程,第1个线程计算从1加到10,第2个线程计算11加到20,...,第10个线程计算91加到100,最后把10个线程结果相加并输出。要求尽量能看到他们交叉输出。要求使用两种方法创建线程:Thread子类创建线程和Thread类直接创建线程对象。
时间: 2024-02-17 10:05:03 浏览: 77
使用Thread子类创建线程的Java代码如下:
```java
public class SumThread extends Thread {
private int start;
private int end;
private int result;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
this.result = 0;
}
public void run() {
for (int i = start; i <= end; i++) {
result += i;
}
}
public int getResult() {
return result;
}
}
public class Main {
public static void main(String[] args) {
SumThread[] threads = new SumThread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new SumThread(i*10+1, i*10+10);
threads[i].start();
}
int result = 0;
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
result += threads[i].getResult();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("总和为:" + result);
}
}
```
使用Thread类直接创建线程对象的Java代码如下:
```java
public class Main {
public static void main(String[] args) {
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
int start = i*10+1;
int end = i*10+10;
threads[i] = new Thread(() -> {
int result = 0;
for (int j = start; j <= end; j++) {
result += j;
}
System.out.println("线程" + (start/10) + "的结果为:" + result);
});
threads[i].start();
}
int result = 0;
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < threads.length; i++) {
int start = i*10+1;
int end = i*10+10;
result += sum(start, end);
}
System.out.println("总和为:" + result);
}
private static int sum(int start, int end) {
int result = 0;
for (int i = start; i <= end; i++) {
result += i;
}
return result;
}
}
```
两种方法的区别在于线程的实现方式不同,但都可以达到相同的效果。注意多线程并发输出可能会出现交叉现象。
阅读全文