java多线程处理,循环遍历耗时操作

it2026-01-31  3

package com.hbis.ttie.lbs.ctrl.rest; import com.hbis.ttie.core.util.UuidUtils; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { /*遍历需要耗时较长的处理*/ public static void main(String[] args) throws Exception{ /*模拟操作开始----》*/ ExecutorService executorService = Executors.newFixedThreadPool(1000);//设置1000个线程 List<Future<Result>> results = new ArrayList<Future<Result>>(); for(int k=0;k<10000;k++){ //拼装入参 User user = new User(); user.setId(UuidUtils.generate16bitUUID()); user.setName("张三"); user.setNo(k + "&" + k); Action task = new Action(user); results.add(executorService.submit(task)); } executorService.shutdown(); for (Future<Result> resultFuture: results){ while (true) { if(resultFuture.isDone() && !resultFuture.isCancelled()) { //多线程处理后,返回的数据 Result result = resultFuture.get(); System.out.println(result.getKey()+"|"+result.getMsg()); break; }else{ Thread.sleep(100); } } } } } package com.hbis.ttie.lbs.ctrl.rest; import java.util.concurrent.Callable; public class Action implements Callable<Result> { private User user; public Action(User user){ this.user = user; } @Override public Result call() throws Exception { Result result = new Result(); try { //睡眠6s,模拟耗时操作 Thread.currentThread().sleep(6000); //拼装入参,模拟返回数据 result.setKey(user.getId()); result.setMsg(user.getName()+user.getNo()); } catch (InterruptedException e) { e.printStackTrace(); } return result; } } package com.hbis.ttie.lbs.ctrl.rest; /*入参类*/ public class User { private String id; private String name; private String no; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } } package com.hbis.ttie.lbs.ctrl.rest; /*结果类*/ public class Result { private String key; private String msg; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }

 

最新回复(0)