zoukankan      html  css  js  c++  java
  • 证明创建runnable实例和普通类时间一样长, 其实吧


    import java.util.concurrent.ConcurrentLinkedQueue;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

    //证明创建runnable实例和普通类时间一样长, 其实这是自己对线程和任务混淆了

    public class Test002 {

    private ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
    // private ArrayList<String> queue = new ArrayList<String>();
    // private CyclicBarrier barrier = new CyclicBarrier(10000000);
    private CountDownLatch latch = new CountDownLatch(100000);
    ExecutorService es = Executors.newFixedThreadPool(4);

    public static void main(String[] args) {
    Test002 test001 = new Test002();
    long timeStart = System.currentTimeMillis();
    test001.begin();
    System.out.println("##线程类实例化10000次时间:"+(System.currentTimeMillis()-timeStart));

    timeStart = System.currentTimeMillis();
    test001.begin2();
    System.out.println("##普通类实例化10000次时间:"+(System.currentTimeMillis()-timeStart));

    }

    public void begin(){
    for (int i = 0; i < 10000; i++) {
    Runnable001 runnable001 = this.new Runnable001(i);
    }
    }
    public void begin2(){
    for (int j = 0; j < 10000; j++) {
    Runnable002 Runnable002 = this.new Runnable002(j);
    // new Thread(); // 时间主要花在创建线程上,使用runnable接口不占用时间
    }
    }

    private class Runnable001 implements Runnable{
    private int value;
    public Runnable001(int value) {
    this.value = value;
    }

    public void run() {

    try {
    // barrier.await();
    } catch (Exception e) {
    e.printStackTrace();
    }
    queue.offer(value + "");
    latch.countDown();//latch计数减一
    }

    }
    private class Runnable002 {
    private int value;
    public Runnable002(int value) {
    this.value = value;
    }

    public void run() {

    try {
    // barrier.await();
    } catch (Exception e) {
    e.printStackTrace();
    }
    queue.offer(value + "");
    latch.countDown();//latch计数减一
    }

    }
    }
  • 相关阅读:
    利用cookie实现iframe刷新时停留在当前页面
    css定位学习经验记录
    用div加css做表格去掉外围边框
    利用css中的background-position定位图片
    css3实现圆形逐渐减少动画
    The Best Path
    3998
    YAPTCHA(hdu2973)
    1556 计算
    1808: 地铁
  • 原文地址:https://www.cnblogs.com/fengdaren/p/9765922.html
Copyright © 2011-2022 走看看