在我自己方法里面调用多线程,线程内赋值给外面会很不确定,因为系统始终快于子线程,所以会在我自己方法先运行到最后才会执行子线程内的方法,导致没有赋值上.如果让程序睡眠一些时间的话,可以取到值,但是这个时间不确定,所以也不可取.
求大神帮忙看看,代码如下:
@ResponseBody @RequestMapping("/upload") public Map<String, Object> upload(@RequestParam(value = "path", required = false) String path, @RequestParam(value = "dns1", required = false) String dns1, @RequestParam(value = "dns2", required = false) String dns2, HttpServletResponse response,HttpServletRequest request)throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String webPath=request.getServletContext().getRealPath(""); //读取TXT文件里面的域名信息 List<String> importTxt = TextUtils.importTxt(new File(webPath + path)); Dns dns = new Dns(); List<Dns> original_datas = new ArrayList<>();//dns1数据 List<Dns> this_datas = new ArrayList<>();//dns2数据 ExecutorService pool = Executors.newFixedThreadPool(10); for (String domain : importTxt) { if (domain == null || domain.isEmpty()) { continue; } else { //解析两份数据 // original_datas.addAll(DnsUtils.getIps(domain, dns1)); // this_datas.addAll(DnsUtils.getIps(domain, dns2)); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { original_datas.addAll(DnsUtils.getIps(domain, dns1)); System.out.println(Thread.currentThread().getName()+" original_datas"); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }); /*Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { this_datas.addAll(DnsUtils.getIps(domain, dns2)); System.out.println(Thread.currentThread().getName()+" this_datas"); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } });*/ pool.execute(thread1); //pool.execute(thread2); this_datas.addAll(DnsUtils.getIps(domain, dns2)); } } pool.shutdown(); //Thread.sleep(10000); System.out.println("original_datas="+original_datas.toString()); System.out.println("this_datas="+this_datas.toString()); //数据对比 List<String> dnsDuibi = MyUtil.dnsDuibi(original_datas,this_datas); dnsService.addList(original_datas); dnsService.addList(this_datas); map.put("msg", "上传成功"); map.put("success", true); //map.clear(); // 原数据比 this_data map.put("original_datas", original_datas); map.put("this_datas", this_datas); map.put("dnsDuibi", dnsDuibi); return map; }
因为我需要用多线程执行的是两行代码,如果用一个子线程去执行其中一条,另一条不用多线程,似乎可行,但是效率还是很低,也会遇到同步的问题.麻烦大神指点下
管道pipe 通信
线程写 pipe.write(dns)
主线程 读取 pipe.read() 没有数据到达前是阻塞的一直等待
Future?CountDownLatch?
无非是效率低点 为什么会遇到同步的麻烦
我这边模拟了你的那个相似场景,大概的伪代码,你看看
//产生数据工具类
//线程工具类
//controller层代码
结果:
Future或者CountDownLatch进行阻塞吧,这里的逻辑必须等待。