多线程处理稀缺资源并返回数据
// +++多线程处理公共方法
public void ThreadealBlogBook(List blogArticleList, final float rowh1, final float wordsize1, final BlogBook blogBook1) {
long start = System.currentTimeMillis();
final Iterator<BlogArticle> iterarticle = blogArticleList.iterator();
int current = 0;
ExecutorService thPool = Executors.newFixedThreadPool(5);
// 这种方式不分线程的顺序,先结束的先返回
CompletionService<PodBook> comPool = new ExecutorCompletionService<PodBook>(thPool);
while (iterarticle.hasNext()) {
final BlogArticle blogArticle = iterarticle.next();
if (null != blogArticle) {
comPool.submit(new Callable<PodBook>() {
@Override
public PodBook call() {
PodBook podbook = new PodBook();
podbook = PodBook.dao.generateBlogBookSGSPThread(blogArticle, rowh1, wordsize1, "10", blogBook1);
return podbook;
}
});
}
}
List<PodBook> podbooks = new ArrayList<PodBook>();
Iterator iter = blogArticleList.iterator();
while (iter.hasNext()) {
try {
iter.next();
System.out.println("size--");
podbooks.add(comPool.take().get());
} catch (Exception e) {
e.printStackTrace();
}
}
thPool.shutdown();
ExecutorService exec = Executors.newFixedThreadPool(5);
final Iterator<BlogArticle> iterarticle1 = blogArticleList.iterator();
ArrayList<Future<PodBook>> results = new ArrayList<Future<PodBook>>();
while (iterarticle1.hasNext()) {
final BlogArticle blogArticle = iterarticle1.next();
results.add(exec.submit(new Callable<PodBook>() {
@Override
public PodBook call() {
PodBook podbook = new PodBook();
podbook = PodBook.dao.generateBlogBookSGSPThread(blogArticle, rowh1, wordsize1, "10", blogBook1);
return podbook;
}
}));
}
Vector<PodBook> podbooks = new Vector<PodBook>();
for(Future<PodBook> fs : results){
try{
System.out.println(current++);
podbooks.add(fs.get());//可以调用很多方法,包括是否工作等等
}catch(Exception e){
e.printStackTrace();
}finally{
exec.shutdown();
}
}
System.out.println("piaban + ");
System.out.println(System.currentTimeMillis() - start);
System.out.println("total" + current);
Db.batch("insert into pod_book (booktemplateid,kaibentempletid,width,height,contenttype,levelid1,"
+ "levelid2,creatime,lastpodxml,totalpage,lastupdatetime,wordcount,title_name,bookhashcode) "
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
"booktemplateid,kaibentempletid,width,height,contenttype,levelid1,levelid2,creatime,lastpodxml,totalpage,lastupdatetime,wordcount,title_name,bookhashcode",
podbooks, 10);
// System.out.println(“use + “);
// System.out.println(System.currentTimeMillis() - start);
}