java使用线程池和非线程池比较

在myeclipse中执行程序,使用jdk自带工具jconsole.exe监测:

1.未使用线程池:

package com.handmessage.concurrent;import java.util.concurrent.CountDownLatch;public class Test { public static void main(String[] args) { CountDownLatch begin = new CountDownLatch(1); CountDownLatch end = new CountDownLatch(1000); Thread[] ts = new Thread[1000]; for (int n = 0; n < 100; n++) { for (int i = 0; i < 1000; i++) { ts[i] = new Thread(new MyThread(n + "-" + i, begin, end)); ts[i].start(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } begin.countDown(); try { end.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }}class MyThread implements Runnable { private String name; private CountDownLatch begin; private CountDownLatch end; public MyThread(String name, CountDownLatch begin, CountDownLatch end) { this.name = name; this.begin = begin; this.end = end; } public void run() { try { begin.await(); System.out.println(name); end.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }

内存、线程数量都在不停增涨,myeclipse卡死掉;

2.使用线程池:

package com.handmessage.concurrent;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Test { public static void main(String[] args) { CountDownLatch begin = new CountDownLatch(1); CountDownLatch end = new CountDownLatch(1000); ExecutorService es = Executors.newFixedThreadPool(1000); for (int n = 0; n < 100; n++) { for (int i = 0; i < 1000; i++) { es.execute(new MyThread(n + "-" + i, begin, end)); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } begin.countDown(); try { end.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }}class MyThread implements Runnable { private String name; private CountDownLatch begin; private CountDownLatch end; public MyThread(String name, CountDownLatch begin, CountDownLatch end) { this.name = name; this.begin = begin; this.end = end; } public void run() { try { begin.await(); System.out.println(name); end.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }

运行平稳,内存在开始创建线程池固定线程数量时增涨较快,之后平稳,线程数也一直维持在线程池配置的线程数量上。

就是对虚怀若谷谦虚谨慎八个字真正理解的人,

java使用线程池和非线程池比较

相关文章:

你感兴趣的文章:

标签云: