首先这是个人在实际的项目中使用的代码,部分敏感代码没有上,不过不影响对代码的理解:

1.实现自己的线程

/**

  • @author
  • TODO:收款率线程
  • /
    public class Thread2CollectionRate implements Runnable{private String sql;private List<Map<String, Object>> listMap ;@Override
    public void run() {
    //此处线程中获取DAO实例是通过spring注入,各位可以根据自己的方式注入
    BaseService service = (BaseService)SpringContextUtil.getService("service");
    List<Map<String, Object>> list = service.getList(sql);System.out.println("run tread ok ..................................." + list.size());
    //添加数据到MAP中去
    if(listMap != null) {
    listMap.addAll(list);
    }

}

public String getSql() {
return sql;
}

public void setSql(String sql) {
this.sql = sql;
}

/**

  • @return the listMap
  • /
    public List<Map<String, Object>> getListMap() {
    return listMap;
    }

/**

  • @param listMap the listMap to set
  • /
    public void setListMap(List<Map<String, Object>> listMap) {
    this.listMap = listMap;
    }

}

2.循环调用线程

String sql = "你的SQL语句";

//定义线程池
ExecutorService e = Executors.newCachedThreadPool();

List<Map<String, Object>> listMap = new LinkedList<Map<String, Object>>();

for(int i = 0 ; i < 6; i++) {
String tempSql = "需要分线程执行的SQL语句";
Thread2CollectionRate tempTread = new Thread2CollectionRate();
//把需要装数据的Map放到线程中去
tempTread.setListMap(listMap);
//把需要执行的SQL放到线程中去
tempTread.setSql(tempSQL);
//执行线程
e.execute(tempTread);

}

//通知关闭线程池
e.shutdown();
//死循环等待线程池完全关闭,只有所有的线程全部执行完毕e.isTerminated()等于true

try {
while(true) {
if(e.isTerminated()) {
//listMap中就是你所需要的全部数据
System.out.println("listMap.size() :" + listMap.size());
break;
}
//每次循环等待250毫秒
Thread.sleep(250);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}

}

原文地址:https://blog.csdn.net/foreversilent/article/details/78602991?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168474995516800188548878%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168474995516800188548878&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-15-78602991-null-null.142^v87^control_2,239^v2^insert_chatgpt&utm_term=java%E4%BC%98%E5%8C%96