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 }
  • 相关阅读:
    springSecurity登陆与退出json形式交互
    SQL-Mysql表结构操作
    SQL-Mysql数据类型
    SQL-SQL事物操作
    springboot之Validation参数校验
    springSecurity之java配置篇
    springsecurity入门篇
    springboot集成shiro
    13个不low的JS数组操作
    基于canvas的五子棋
  • 原文地址:https://www.cnblogs.com/sherrykid/p/4598898.html
Copyright © 2011-2022 走看看