编写10个线程,第一个线程从1加到10
时间: 2023-04-25 22:03:00 浏览: 143
,第二个线程从11加到20,以此类推,直到第十个线程从91加到100。
这个问题可以使用Java编程语言来解决。下面是一个可能的解决方案:
```java
public class ThreadExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
int start = (i - 1) * 10 + 1;
int end = i * 10;
Thread t = new Thread(new MyRunnable(start, end));
t.start();
}
}
}
class MyRunnable implements Runnable {
private int start;
private int end;
public MyRunnable(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = ;
for (int i = start; i <= end; i++) {
sum += i;
}
System.out.println("Thread " + Thread.currentThread().getId() + " sum: " + sum);
}
}
```
这个程序创建了10个线程,每个线程都有一个起始值和结束值。每个线程都会计算从起始值到结束值的和,并输出结果。在主线程中,我们使用循环来创建这些线程,并启动它们。每个线程都是一个实现了Runnable接口的类的实例。在run()方法中,我们使用一个循环来计算和,并输出结果。注意,我们使用Thread.currentThread().getId()方法来获取当前线程的ID,以便在输出中区分不同的线程。