首页
随机
最近更改
特殊页面
社群首页
参数设置
关于WHY42
免责声明
WHY42
搜索
用户菜单
登录
欢迎来到Riguz的小站!这是一个私人wiki,用来记录一些我的笔记。
查看“︁Java Threadpool”︁的源代码
←
Java Threadpool
因为以下原因,您没有权限编辑该页面:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
JDK提供了ExecutorService以提供线程池的应用,今天测试了一下线程池的使用,受益匪浅。 =线程计数= 使用CountDownLatch锁来对线程执行结果进行倒数,当所有线程执行完之后,计算出耗时。 <source lang="java"> static final int testCount = 1000000; static final int sleep = 10; public static void main(String[] args){ System.out.println("Hello!"); HelloPool hold = new HelloPool(); Date t1 = new Date(); hold.normalThread(); Date t2 = new Date(); System.out.println("\nNormal cost:" + (t2.getTime() - t1.getTime())); t1 = new Date(); hold.useThreadPool(); t2 = new Date(); System.out.println("\nNormal cost:" + (t2.getTime() - t1.getTime())); } </source> =不使用线程池= <source lang="java"> 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(); } } </source> =使用线程池= <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> [[Category:Programe]]
返回
Java Threadpool
。