要求从1到100000000累加计算?怎么用多线程实现,要求性能?
解决方案 »
- JSON问题
- document.forms(0).submit()为什么迟迟之后,才执行
- oracle.sql.BLOB与 java.sql.Blob 区别,请高人指点!
- 探讨:淘宝的分类搜索运用何种技术,及思路
- 急问关于action forward问题~~在线等待~
- 怎么操作记录集
- JDBC连接SQLSERVER2000数据库出错误,请帮助解决。出现问题如下:
- hibernate问题(急),在线等待
- 有关于struts的书籍吗?知情者请告知,谢谢
- 学习EJB CMP/CMR 的心得体会
- sql语句中排序时怎么同时满足两个条件
- 求助hibernateTemplate中怎么用Group By查询?
long sum = 0; //最终总和
int count = 1; //线程数
int total = 0; //要累加的数据
public Test(int count, int total) {
this.count = count;
this.total = total;
} public void start() {
int n = count;
int avg = total / n; //把数据分割成n个部分
int from = 0, to = 0;
for (int i=0; i<n; i++) {
from = (to == 0 ? i * avg + 1 : to);
to = (i==n-1 ? total+1 : from + avg);
new TestThread(from, to).start(); //每个线程处理一部分数据
}
while (count > 0) { //等待所有线程执行完成
Thread.yield();
}
System.out.printf("multi-thread: sum=%d\n", sum); //打印结果
} public synchronized void update(long value) { //更新最终总和
this.sum += value;
this.count--;
} class TestThread extends Thread { //线程
int from, to;
public TestThread(int from, int to) {
this.from = from;
this.to = to;
}
public void run() {
long s = 0;
for (int i=from; i<to; i++) { //线程处理一部分数据
s += i;
}
Test.this.update(s); //更新最终总合
}
} public static void main(String[] args) {
int n = 15, total = 100000000;
new Test(n, total).start();
long sum = 0;
for (int i=0; i<total; i++) {
sum += (i+1);
}
System.out.printf("single-thread: sum=%d\n", sum);
}
}