今天在书上看到一个题目:编写10个线程,第一个从1加到10,第二个从11加到20......第10个从91加到100.最后再把10个线程的结果相加.
跪求更合理的方法,感觉自己这个新人写的代码好丑,
附代码(静态成员变量设置成public是为了方便,懒得写set get方法,不要在意这些细节:loveliness:):
- class Sum implements Runnable {
- private int start;
- private int end;
- public int sum = 0; // 每个对象的数值累加最终的和
- public static int count = 0; // 计数器
- private static Object obj = new Object(); // 锁
- // 构造方法,初始化加法的开始和结束的值
- Sum(int start, int end) {
- // TODO Auto-generated constructor stub
- this.start = start;
- this.end = end;
- }
- // 线程方法
- public void run() {
- for (int i = this.start; i <= this.end; i++) {
- synchronized (obj) {
- this.sum = this.sum + i;
- count++;
- System.out.println(Thread.currentThread().getName() + "..."
- + sum);
- }
- }
- }
- }
- public class SumThreadTest {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Sum s1 = new Sum(1, 10);
- Sum s2 = new Sum(11, 20);
- Sum s3 = new Sum(21, 30);
- Sum s4 = new Sum(31, 40);
- Sum s5 = new Sum(41, 50);
- Sum s6 = new Sum(51, 60);
- Sum s7 = new Sum(61, 70);
- Sum s8 = new Sum(71, 80);
- Sum s9 = new Sum(81, 90);
- Sum s10 = new Sum(91, 100);
- new Thread(s1).start();
- new Thread(s2).start();
- new Thread(s3).start();
- new Thread(s4).start();
- new Thread(s5).start();
- new Thread(s6).start();
- new Thread(s7).start();
- new Thread(s8).start();
- new Thread(s9).start();
- new Thread(s10).start();
- // 用while(true) +计数器count保证主线程最后结束
- while (true) {
- if (Sum.count == 100) {
- int sum = s1.sum + s2.sum + s3.sum + s4.sum + s5.sum + s6.sum
- + s7.sum + s8.sum + s9.sum + s10.sum;
- System.out.println(".........." + sum);
- break;
- }
- }
- }
- }
复制代码 |
|