zoukankan      html  css  js  c++  java
  • Java多线程实践

    1.实现Runnable接口

     1 import java.util.Random;
     2 
     3 
     4 public class PrintTask implements Runnable{
     5     private final int sleepTime;
     6     private final String taskName;
     7     private final static Random generator = new Random();
     8     
     9     
    10     public PrintTask(String name) {
    11         taskName = name;
    12         sleepTime = generator.nextInt(5000);
    13     }
    14 
    15     @Override
    16     public void run() {
    17         try {
    18             System.out.printf("%s going to Sleep for %d milliseconds.
    ",
    19                     taskName, sleepTime);
    20             Thread.sleep(sleepTime);
    21         } catch (InterruptedException e) {
    22             System.out.printf("%s %s
    ", taskName, "terminated prematurely" +
    23                     " due to interruption");
    24         }
    25         System.out.printf("%s done sleeping
    ", taskName);
    26     }
    27 
    28 }

    2.使用ExecutorService管理执行PrintTask的线程

     1 import java.util.Random;
     2 
     3 
     4 public class PrintTask implements Runnable{
     5     private final int sleepTime;
     6     private final String taskName;
     7     private final static Random generator = new Random();
     8     
     9     
    10     public PrintTask(String name) {
    11         taskName = name;
    12         sleepTime = generator.nextInt(5000);
    13     }
    14 
    15     @Override
    16     public void run() {
    17         try {
    18             System.out.printf("%s going to Sleep for %d milliseconds.
    ",
    19                     taskName, sleepTime);
    20             Thread.sleep(sleepTime);
    21         } catch (InterruptedException e) {
    22             System.out.printf("%s %s
    ", taskName, "terminated prematurely" +
    23                     " due to interruption");
    24         }
    25         System.out.printf("%s done sleeping
    ", taskName);
    26     }
    27 
    28 }

    3.执行结果

    可以看到,由于每个任务随机休眠时间不同,执行结束的顺序是不同的。

  • 相关阅读:
    :where()和:is()
    响应式布局(媒体查询+rem)
    v-html的问题及解决办法
    Sticky Footer(粘性页脚)
    css多行文字垂直居中
    BFC
    margin负值的情况
    windows系统设置环境变量
    hash和history原生事件
    腾讯WeTest零售行业质量解决方案
  • 原文地址:https://www.cnblogs.com/zhaoyu1995/p/5741537.html
Copyright © 2011-2022 走看看