zoukankan      html  css  js  c++  java
  • 多线程 线程池 ExecutorService

     1 package org.zln.thread;
     2 
     3 import java.util.Date;
     4 import java.util.concurrent.ExecutorService;
     5 import java.util.concurrent.Executors;
     6 
     7 /**
     8  * Created by sherry on 000024/6/24 22:50.
     9  */
    10 public class TestExecutorService implements Runnable{
    11     public static void main(String[] args) {
    12         new Thread(new TestExecutorService()).start();
    13         System.out.println(new Date()+"主线程结束");
    14     }
    15 
    16     /*之所以将for循环写在一个run中,是为了防止线程池等待过程中造成的主线程堵塞*/
    17     @Override
    18     public void run() {
    19         /*创建一个大小为3的线程池*/
    20         ExecutorService executorService = Executors.newFixedThreadPool(3);
    21         for (int i = 0; i < 20; i++) {
    22             Runnable runnable = new Runnable() {
    23                 @Override
    24                 public void run() {
    25                     long time = (long)(Math.random()*1000);
    26                     System.out.println(new Date()+"休眠:"+time+" 毫秒");
    27                     try {
    28                         Thread.sleep(time);
    29                     } catch (InterruptedException e) {
    30                         e.printStackTrace();
    31                     }
    32                 }
    33             };
    34             /*启动一个线程*/
    35             executorService.execute(runnable);
    36         }
    37         /*线程池必须使用shutdown显示关闭,否则当前线程无法退出*/
    38         executorService.shutdown();
    39     }
    40 }
  • 相关阅读:
    史上自定义 JavaScript 函数Top 10
    switch
    (不)扩展内置原型((Not) Augmenting Built-in Prototypes)
    for-in循环(for-in Loops)
    for
    在dreamweaver中设置php服务器F12预览的方法介绍
    method
    CSS中background-image【CSS Sprites,base64编码】
    shell编程中的小问题
    常见的linux问题积累
  • 原文地址:https://www.cnblogs.com/sherrykid/p/4598898.html
Copyright © 2011-2022 走看看