java编程:编写10个线程第一个线程从1加到10第二个线程从11加20…第九个线程从91加到100最后再把9个线程结果相加。
以下是一个示例代码,用于实现上述要求:
public class ThreadExample {
private static int sum = 0;
public static void main(String[] args) {
Thread[] threads = new Thread[10];
for (int i = 0; i < 9; i++) {
int start = i * 10 + 1;
int end = start + 9;
threads[i] = new Thread(new SumThread(start, end));
threads[i].start();
}
for (int i = 0; i < 9; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Sum: " + sum);
}
private static class SumThread implements Runnable {
private int start;
private int end;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
int threadSum = 0;
for (int i = start; i <= end; i++) {
threadSum += i;
}
synchronized (ThreadExample.class) {
sum += threadSum;
}
}
}
}
这个例子创建了10个线程,每个线程负责计算一段连续的数字的和。每个线程的起始数字和结束数字通过构造函数传入,然后在线程的 run() 方法中执行计算,并将结果累加到共享的 sum 变量中。在 run() 方法中,使用 synchronized 关键字确保对共享变量的访问是同步的。
最后,主线程等待所有子线程执行完毕,并输出最终的和
原文地址: http://www.cveoy.top/t/topic/ilG4 著作权归作者所有。请勿转载和采集!