公司面試題——線程數組求和

編程題:
 說明: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. }  

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