• 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.执行结果

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

  • 相关阅读:
    DES加密、解密字符串算法(java版)
    浅谈Base64编码
    Flex 捕获摄像头拍照
    java 图片加密
    Flex 应用Remote与后台通信
    flex和后端的数据交互(一)--XML和HTTPService
    web软件业已成为传统软件业的掘墓人(转)
    MS AJAX类库的回调函数中不能使用window.open()
    客户端如何获取服务器控件的值(原理与实例)
    常用正则式收集(增加中)
  • 原文地址:https://www.cnblogs.com/zhaoyu1995/p/5741537.html
Copyright © 2020-2023  润新知