用Java实现:编写程序:创建10个线程,第一个线程计算从1加到10,第二个线程算11加到20......,第十个线程计算91加到100,最后把10个线程结果相加并输出。要求尽量能看到他们交叉输出。要求用两种方法创建线程:Thread子类创建和Thread类直接创建线程对象。
时间: 2024-02-17 18:02:55 浏览: 32
使用Thread子类创建线程的实现代码:
```
public class SumThread extends Thread {
private int start;
private int end;
private int sum;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
}
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
System.out.println(Thread.currentThread().getName() + " computes sum of " + i);
}
}
}
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 + 1) * 10);
threads[i].start();
}
int result = 0;
for (SumThread thread : threads) {
try {
thread.join();
result += thread.getSum();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("The result is " + result);
}
}
```
使用Thread类直接创建线程对象的实现代码:
```
public class SumRunnable implements Runnable {
private int start;
private int end;
private int sum;
public SumRunnable(int start, int end) {
this.start = start;
this.end = end;
}
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
System.out.println(Thread.currentThread().getName() + " computes sum of " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
SumRunnable runnable = new SumRunnable(i * 10 + 1, (i + 1) * 10);
threads[i] = new Thread(runnable);
threads[i].start();
}
int result = 0;
for (Thread thread : threads) {
try {
thread.join();
SumRunnable runnable = (SumRunnable) thread.getRunnable();
result += runnable.getSum();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("The result is " + result);
}
}
```
注意,为了能够看到线程交替输出,可以在run方法中加入一句打印语句,以便观察每个线程计算的过程。