使用java编写程序:创建10个线程,第1个线程计算从1加到10,第2个线程计算11加到20,...,第10个线程计算91加到100,最后把10个线程结果相加并输出。要求尽量能看到他们交叉输出。要求使用两种方法创建线程:Thread子类创建线程和Thread类直接创建线程对象。
时间: 2024-02-17 11:05:02 浏览: 65
使用Thread子类创建线程的代码如下:
```
class MyThread extends Thread {
private int start;
public MyThread(int start) {
this.start = start;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i <= start + 9; i++) {
sum += i;
}
System.out.println(Thread.currentThread().getName() + "计算结果为:" + sum);
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread[] threads = new MyThread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new MyThread(i * 10 + 1);
threads[i].start();
}
int totalSum = 0;
for (int i = 0; i < 10; i++) {
threads[i].join();
totalSum += threads[i].getResult();
}
System.out.println("总结果为:" + totalSum);
}
}
```
使用Thread类直接创建线程对象的代码如下:
```
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
final int start = i * 10 + 1;
threads[i] = new Thread(() -> {
int sum = 0;
for (int j = start; j <= start + 9; j++) {
sum += j;
}
System.out.println(Thread.currentThread().getName() + "计算结果为:" + sum);
});
threads[i].start();
}
int totalSum = 0;
for (int i = 0; i < 10; i++) {
threads[i].join();
totalSum += threads[i].getResult();
}
System.out.println("总结果为:" + totalSum);
}
}
```
其中,getResult()方法是在MyThread类中自定义的,用于获取计算结果。
阅读全文