您的位置:首页 > 其它

主线程里创建N个子线程,等待N个子线程全部执行完

2014-04-30 17:10 162 查看
1.主线程里创建N个子线程,等待N个子线程全部执行完后,打印每个子线程执行的时间。

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* 主线程里创建N个子线程,等待N个子线程全部执行完后,打印每个子线程执行的时间。
* 一种可行的方法
*/
public class MainThread {

public static void main(String[] args) throws InterruptedException {
int threadNum = 5;
CountDownLatch latch = new CountDownLatch(threadNum);
Map<String, Long> map = new ConcurrentHashMap<String, Long>(threadNum);
ExecutorService pool = Executors.newFixedThreadPool(threadNum);
for (int i=0; i < threadNum; i++) {
pool.submit(new SubThread(latch, map));
}
latch.await(); //计数减到0时一直等待

for (Map.Entry<String, Long> entry : map.entrySet()) {
System.out.println(entry.getKey() + "执行耗时:" + entry.getValue() + "毫秒");
}

pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
System.err.println("Pool did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}

}

class SubThread implements Runnable {
private CountDownLatch latch;
private Map<String, Long> map;

public SubThread(CountDownLatch latch, Map<String, Long> map) {
this.latch = latch;
this.map = map;
}

@Override
public void run() {
long start = System.currentTimeMillis();
System.out.println(Thread.currentThread() + "开始执行...");
try {
Thread.sleep(1000); //模拟执行操作
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println(Thread.currentThread() + "执行完毕");
map.put(Thread.currentThread().toString(), end-start);
}

}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐