线程处理的一个实际例子:
@Service public class SynAsynThreadTestServiceImpl implements SynAsynThreadTestService { private static final Logger logger = Logger.getLogger(SynAsynThreadTestServiceImpl.class); private static int nThreads = Runtime.getRuntime().availableProcessors() * 2 + 1; @Autowired private ProdMapper prodMapper; private static ExecutorService executors = Executors.newFixedThreadPool(nThreads, new ThreadFactory() { private final String threadNamePrefix = "si_query_task_"; private final AtomicInteger count = new AtomicInteger(1); @Override public Thread newThread(Runnable r) { Thread t = new Thread(Thread.currentThread().getThreadGroup(), r, threadNamePrefix + count.getAndIncrement()); t.setDaemon(true); return t; } }); @Override public ProdSerDTO searchProd(String word) { String url = "https://suggest.taobao.com/sug?code=utf-8&q=" + URLencord.getURLEncoderString(word) + "&callback=cb"; String response = HttpRequestUtils.getRequest(url, "0"); LoggerUtil.info(logger, "请求出参:{0}", response); if (response != null) { ProdSerDTO dto = JSON.parseObject(response, ProdSerDTO.class); for (int i = 0; i < dto.getResult().size(); i++) { SaveInfoProcessor saveInfoProcessor=new SaveInfoProcessor(); saveInfoProcessor.setProdMapper(prodMapper); ProdDO pDo=new ProdDO(); List<Object> list =JSONArray.parseArray( dto.getResult().get(i)); pDo.setPname(list.get(0).toString()); pDo.setPnum(list.get(1).toString()); saveInfoProcessor.setProdDo(pDo); LoggerUtil.info(logger, "i:{0},参数:{1}",i, pDo); executors.submit(saveInfoProcessor); } return dto; } return null; } }
public class SaveInfoProcessor implements Runnable{ private static final Logger logger =Logger.getLogger(SaveInfoProcessor.class); private ProdDO prodDo; private ProdMapper prodMapper; public ProdDO getProdDo() { return prodDo; } public void setProdDo(ProdDO prodDo) { this.prodDo = prodDo; } public ProdMapper getProdMapper() { return prodMapper; } public void setProdMapper(ProdMapper prodMapper) { this.prodMapper = prodMapper; } @Override public void run() { LoggerUtil.info(logger, "线程:{0},存入:{1}",Thread.currentThread().getName(), prodDo); prodMapper.insert(prodDo); } }
附项目地址:https://gitee.com/zyf6303/flowexample
注:项目是一个springboot测试项目,一直在更新完善中,希望大神们指点一二