/*
* @TODO 线程池测试
*/
@Test
public void threadPool(){
/*java提供的统计线程运行数,一开始设置其值为50000,每一个线程任务执行完
* 调用CountDownLatch#coutDown()方法(其实就是自减1)
* 当所有的线程都执行完其值就为0
*/
CountDownLatch count = new CountDownLatch(50000);
long start = System.currentTimeMillis();
Executor pool = Executors.newFixedThreadPool(10);//开启线程池最多会创建10个线程
for(int i=0;i<50000;i++){
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("hello");
count.countDown();
}
});
}
while(count.getCount()!=0){//堵塞等待5w个线程运行完毕
}
long end = System.currentTimeMillis();
System.out.println("50个线程都执行完了,共用时:"+(end-start)+"ms");
}
/**
*@TODO 手动创建线程测试
*/
@Test
public void thread(){
CountDownLatch count = new CountDownLatch(50000);
long start = System.currentTimeMillis();
for(int i=0;i<50000;i++){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello");
count.countDown();
}
});
thread.start();
}
while(count.getCount()!=0){//堵塞等待5w个线程运行完毕
}
long end = System.currentTimeMillis();
System.out.println("50000个线程都执行完了,共用时:"+(end-start)+"ms");
}
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有