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

最近在做接口的时候总是遇到一个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 list = new ArrayList();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值