多线程和单线程 打印数字到100000 的速度对比

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**

  • @author silence

  • 多线程和单线程 打印数字到100000 的速度对比
    */
    public class Demo2 {
    public static void main(String[] args) {
    //循环次数
    int number = 5000000;
    //单线程 耗时毫秒:3349 : 1000000
    // ontThread(number);

     //10条线程 耗时毫秒:4356
     tenThread(number);
    

    }

    /**

    • 多线程
    • @param number 循环次数
      */
      private static void tenThread(int number) {
      long start = System.currentTimeMillis();
      ThreadPoolExecutor thread = new ThreadPoolExecutor(
      //核心线程数
      10,
      //最大线程数
      10,
      //等待时间
      10,
      //等待单位
      TimeUnit.SECONDS,
      //排队阻塞队列
      new ArrayBlockingQueue<>(1),
      //线程工厂
      Executors.defaultThreadFactory(),
      //拒绝策略
      new ThreadPoolExecutor.AbortPolicy()
      );
      MyRunnable myRunnable = new MyRunnable(number);
      for (int i = 0; i < 10; i++) {
      thread.submit(myRunnable);
      }
      //结束线程池
      thread.shutdown();
      //一致在这里等多线程执行完毕,计算毫秒数
      while (true) {
      //等所有线程执行完,否则一直等
      if (thread.isTerminated()) {
      long end = System.currentTimeMillis();
      System.out.println(“耗时毫秒:” + (end - start));
      break;
      }
      }
      }

    //线程实现类
    static class MyRunnable implements Runnable {
    private static int count = 0;
    private int number;

     public MyRunnable() {
     }
    
     public MyRunnable(int number) {
         this.number = number;
     }
    
     @Override
     public void run() {
         while (count < number) {
    

// System.out.print(Thread.currentThread().getName() + " = ");
System.out.println(count++);
}
}
}

/**
 * @param number 循环次数
 */
private static void ontThread(int number) {
    long start = System.currentTimeMillis();
    int count = 0;
    for (; count < number; count++) {
        System.out.println(count);
    }
    long end = System.currentTimeMillis();
    System.out.println("耗时毫秒:" + (end - start) + " : " + count);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Silence丶你的名字

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值