java在for循环中使用concurrent包进行多线程编程

来源:互联网 发布:淘宝在手机上怎么投诉 编辑:程序博客网 时间:2024/06/17 00:46

  最近在做接口的时候总是遇到一个for语句中 每次循环会涉及很多资源,包括 ftp io db,总想用现场来控制太.找到一篇文章  http://daoger.javaeye.com/blog/142485 写的不错.自己写了2个demo

1. 主线程不等待

 public class CopyOfTestThreadPool {
 public static void main(String args[]) throws InterruptedException {
  // only two threads

  ExecutorService exec = Executors.newFixedThreadPool(20);
  List<Long> list = new ArrayList<Long>();
  for(int index = 0; index < 1000000; index++){
   list.add(System.nanoTime());
  }
  
  long start = System.currentTimeMillis();
  for (Long long1 : list) {
   final Long l = long1;
   exec.execute(new Runnable(){

    public void run() {
     System.out.println(l);
     try {
      Thread.sleep(5000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     
    }});
  }
  // must shutdown
  exec.shutdown();
   long end = System.currentTimeMillis();
   System.out.print("共计用时 ");
   System.out.println(end  - start);
 }
}

2 主线程会等待

public class TestCountDownLatch {
 public static void main(String[] args) throws InterruptedException {
  long start = System.currentTimeMillis();
  // 开始的倒数锁
  final CountDownLatch begin = new CountDownLatch(1);
  // 结束的倒数锁
  final CountDownLatch end = new CountDownLatch(10000);
  // 十名选手
  final ExecutorService exec = Executors.newFixedThreadPool(10);
  for (int index = 0; index < 10000; index++) {
   final int NO = index + 1;
   Runnable run = new Runnable() {
    public void run() {
     try {
      begin.await();
      Thread.sleep((long) (Math.random() *  10));
     } catch (InterruptedException e) {
     } finally {
      end.countDown();
     }
    }
   };
   exec.submit(run);
  }
  System.out.println("Game Start");
  begin.countDown();
  end.await();
  System.out.println("Game Over");
  exec.shutdown();
   System.out.print("共计用时 ");
   System.out.println(System.currentTimeMillis()  - start);
 }
}

 

详细看上面那位老兄的blog