Java Threadpool:修订间差异
imported>Soleverlee 以“JDK提供了ExecutorService以提供线程池的应用,今天测试了一下线程池的使用,受益匪浅。 =不使用线程池= <source lang="java"> void nor...”为内容创建页面 |
imported>Soleverlee |
||
第26行: | 第26行: | ||
=使用线程池= | =使用线程池= | ||
<source lang="java"> | <source lang="java"> | ||
void useThreadPool(){ | |||
final CountDownLatch lock = new CountDownLatch(testCount); | |||
final ExecutorService pool = Executors.newCachedThreadPool(); | |||
for(int i = 0; i < testCount; i++){ | |||
final int item = i; | |||
pool.execute(new Runnable(){ | |||
@Override | |||
public void run() { | |||
handle(item); | |||
lock.countDown(); | |||
} | |||
}); | |||
} | |||
try { | |||
lock.await(); | |||
pool.shutdown(); | |||
} catch (InterruptedException e) { | |||
e.printStackTrace(); | |||
} | |||
} | |||
</source> | </source> | ||
[[Category:Programe]] | [[Category:Programe]] |
2016年3月18日 (五) 03:10的版本
JDK提供了ExecutorService以提供线程池的应用,今天测试了一下线程池的使用,受益匪浅。
不使用线程池
void normalThread(){
final CountDownLatch lock = new CountDownLatch(testCount);
for(int i = 0; i < testCount; i++){
final int item = i;
Thread t = new Thread(new Runnable(){
@Override
public void run() {
handle(item);
lock.countDown();
}
});
t.start();
}
try {
lock.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
使用线程池
void useThreadPool(){
final CountDownLatch lock = new CountDownLatch(testCount);
final ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 0; i < testCount; i++){
final int item = i;
pool.execute(new Runnable(){
@Override
public void run() {
handle(item);
lock.countDown();
}
});
}
try {
lock.await();
pool.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}