zoukankan      html  css  js  c++  java
  • 动态创建线程(多线程)处理大量数据

     1 import java.util.List;
     2 import java.util.concurrent.CountDownLatch;
     3 import java.util.concurrent.ExecutorService;
     4 import java.util.concurrent.Executors;
     5 
     6 public class BatchDownLoadNeLogByThread {
     7     // 导入数据
     8     public boolean importData(List<String> list) {
     9     
    10         // 线程数
    11         int RunSize =list.size();
    12         // 创建一个线程池
    13     //    ThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(RunSize);
    14         ExecutorService executor = Executors.newCachedThreadPool();
    15     //    ExecutorService executor = Executors.newSingleThreadExecutor();
    16         CountDownLatch countDownLatch = new CountDownLatch(RunSize);
    17         try {
    18             for (int i = 0; i < RunSize; i++) {
    19                 String newlist = list.get(i);
    20                 ImportTask task = new ImportTask(newlist, countDownLatch);
    21                 executor.execute(task);
    22             }
    23             countDownLatch.await();// 主线程等待所有线程完成任务
    24         } catch (InterruptedException e) {
    25             // TODO Auto-generated catch block
    26             e.printStackTrace();
    27             return false;
    28         } 
    29         // 所有线程完成任务后的一些业务
    30         System.out.println("数据下载完成!");
    31         // 关闭线程池
    32         executor.shutdown();
    33         return true;
    34 
    35     }
    36 
    37     class ImportTask implements Runnable {
    38         private String newNe;
    39         private CountDownLatch countDownLatch;
    40 
    41         public ImportTask( String newNe, CountDownLatch countDownLatch) {
    42             this.newNe = newNe;
    43             this.countDownLatch = countDownLatch;
    44         }
    45 
    46         @Override
    47         public void run() {
    48             boolean flag1 = false;
    49             try {
    50                 
    51                 if (newNe != null) {
    52                     // 业务逻辑
    53                     
    54                 }
    55             } catch (Exception e) {
    56                 // TODO Auto-generated catch block
    57                 e.printStackTrace();
    58             }finally{
    59                 countDownLatch.countDown();// 发出线程任务完成的信号
    60             }
    61 
    62         }
    63     }
    64 
    65 }
  • 相关阅读:
    阿里云CentOS安装firefox闪退
    error: QApplication: No such file or directory
    CentOS下自动登陆root帐户
    Linux下常用软件
    【记录】haphost免费vps初始配置
    检测Linux VPS是Xen、OpenVZ还是KVM真假方法
    使用VNC远程管理VPS(Centos系统)
    配置suricata
    NGUI的输入框制作(attach- input filed script的使用)
    NGUI技能CD效果制作(sprite的type:filled)
  • 原文地址:https://www.cnblogs.com/lhq1996/p/13025778.html
Copyright © 2011-2022 走看看