加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

Java线程池的四种用法与行使场景

发布时间:2019-10-30 01:28:33 所属栏目:建站 来源:小涛
导读:一、如下方法存在的题目 newThread(){ @Override publicvoidrun(){ //营业逻辑 } }.start(); 1、起首频仍的建设、烧毁工具是一个很耗损机能的工作;2、假如用户量较量大,导致占用过多的资源,也许会导致我们的处事因为资源不敷而宕机;3、综上所述,在现实

测试一

  1. public static void method_02() { 
  2.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); 
  3.  
  4.     executor.scheduleAtFixedRate(new Runnable() { 
  5.         @Override 
  6.         public void run() { 
  7.             long start = new Date().getTime(); 
  8.             System.out.println("scheduleAtFixedRate 开始执行时刻:" + 
  9.                     DateFormat.getTimeInstance().format(new Date())); 
  10.             try { 
  11.                 Thread.sleep(5000); 
  12.             } catch (InterruptedException e) { 
  13.                 e.printStackTrace(); 
  14.             } 
  15.             long end = new Date().getTime(); 
  16.             System.out.println("scheduleAtFixedRate 执行耗费时刻=" + (end - start) / 1000 + "m"); 
  17.             System.out.println("scheduleAtFixedRate 执行完成时刻:" + DateFormat.getTimeInstance().format(new Date())); 
  18.             System.out.println("======================================"); 
  19.         } 
  20.     }, 1, 5, TimeUnit.SECONDS); 

执行功效

Java线程池的四种用法与行使场景

测试二

Java线程池的四种用法与行使场景

总结:以上两种方法差异的处所是使命的执行时刻,假如隔断时刻大于使命的执行时刻,使命不受执行时刻的影响。假如隔断时刻小于使命的执行时刻,那么使命执行竣事之后,会立马执行,至此隔断时刻就会被打乱。

  • scheduleWithFixedDelay

测试一

  1. public static void method_03() { 
  2.     ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
  3.  
  4.     executor.scheduleWithFixedDelay(new Runnable() { 
  5.         @Override 
  6.         public void run() { 
  7.             long start = new Date().getTime(); 
  8.             System.out.println("scheduleWithFixedDelay 开始执行时刻:" + 
  9.                     DateFormat.getTimeInstance().format(new Date())); 
  10.             try { 
  11.                 Thread.sleep(1000); 
  12.             } catch (InterruptedException e) { 
  13.                 e.printStackTrace(); 
  14.             } 
  15.             long end = new Date().getTime(); 
  16.             System.out.println("scheduleWithFixedDelay执行耗费时刻=" + (end - start) / 1000 + "m"); 
  17.             System.out.println("scheduleWithFixedDelay执行完成时刻:" 
  18.                     + DateFormat.getTimeInstance().format(new Date())); 
  19.             System.out.println("======================================"); 
  20.         } 
  21.     }, 1, 2, TimeUnit.SECONDS); 

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读