公司面试题——线程数组求和

编程题:
 说明:1)用多线程的方式对inputs数组的每个元素作求和运算,例如某个元素为45,则计算:1+2+3+....+45
       2)把计算结果放到outputs数组对应的索引的位置,例如:
        inputs为:2,3,0,1 计算后outputs为:3,6,0,1
        假定:outputs和inputs数组的元素个数一样
        完成后,程序的最后会打印输入和正确的结果各一行上

实现代码:

[java] view plaincopy
  1. package com.image.common.util;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class TestMain {  
  7.     public static void main(String[] args) {  
  8.         int[] inputs = new int[]{2,3,0,1};  
  9.         int[] outputs = new int[inputs.length];  
  10.           
  11.         List<TestThread> list = new ArrayList<TestThread>();  
  12.         TestThread temp = null;  
  13.         for(int i=0;i<inputs.length;i++){  
  14.             temp = new TestThread(inputs[i]);  
  15.             list.add(temp);  
  16.             temp.start();  
  17.         }  
  18.         for (int i = 0; i < list.size(); i++) {  
  19.             try {  
  20.                 list.get(i).join();  
  21.             } catch (InterruptedException e) {  
  22.                 e.printStackTrace();  
  23.             }  
  24.         }  
  25.           
  26.         String result = "";  
  27.         for (int i = 0; i < list.size(); i++) {  
  28.             outputs[i] = list.get(i).getResult();  
  29.             result = result + outputs[i] + ",";  
  30.         }  
  31.         System.out.println("结果:"+result);  
  32.     }  
  33. }  
  34.   
  35. class TestThread extends Thread{  
  36.       
  37.     private int operation;  
  38.     private int result;  
  39.       
  40.     public TestThread(int operation){  
  41.         this.operation = operation;  
  42.     }  
  43.   
  44.     public void run() {  
  45.         for (int i = 1; i <= operation; i++) {  
  46.             result += i ;  
  47.         }  
  48.     }  
  49.       
  50.     public int getOperation() {  
  51.         return operation;  
  52.     }  
  53.   
  54.     public void setOperation(int operation) {  
  55.         this.operation = operation;  
  56.     }  
  57.   
  58.     public int getResult() {  
  59.         return result;  
  60.     }  
  61.   
  62.     public void setResult(int result) {  
  63.         this.result = result;  
  64.     }  
  65. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章