编程题:
说明:1)用多线程的方式对inputs数组的每个元素作求和运算,例如某个元素为45,则计算:1+2+3+....+45
2)把计算结果放到outputs数组对应的索引的位置,例如:
inputs为:2,3,0,1 计算后outputs为:3,6,0,1
假定:outputs和inputs数组的元素个数一样
完成后,程序的最后会打印输入和正确的结果各一行上
实现代码:
- package com.image.common.util;
- import java.util.ArrayList;
- import java.util.List;
- public class TestMain {
- public static void main(String[] args) {
- int[] inputs = new int[]{2,3,0,1};
- int[] outputs = new int[inputs.length];
- List<TestThread> list = new ArrayList<TestThread>();
- TestThread temp = null;
- for(int i=0;i<inputs.length;i++){
- temp = new TestThread(inputs[i]);
- list.add(temp);
- temp.start();
- }
- for (int i = 0; i < list.size(); i++) {
- try {
- list.get(i).join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- String result = "";
- for (int i = 0; i < list.size(); i++) {
- outputs[i] = list.get(i).getResult();
- result = result + outputs[i] + ",";
- }
- System.out.println("结果:"+result);
- }
- }
- class TestThread extends Thread{
- private int operation;
- private int result;
- public TestThread(int operation){
- this.operation = operation;
- }
- public void run() {
- for (int i = 1; i <= operation; i++) {
- result += i ;
- }
- }
- public int getOperation() {
- return operation;
- }
- public void setOperation(int operation) {
- this.operation = operation;
- }
- public int getResult() {
- return result;
- }
- public void setResult(int result) {
- this.result = result;
- }
- }