zoukankan      html  css  js  c++  java
  • 使用jdk自带的线程池。加载10个线程。

    在开发中使用线程,经常不经意间就new Thread()一个出来,然后发现,这样做不是很好,特别是很多线程同时处理的时候,会出现CPU被用光导致机器假死,线程运行完成自动销毁后,又复活的情况。

    所以在这个时候,就需要使用到线程池。。

    线程池就是类似数据库连接池,限定一个规定大小的连接数(线程数),然后,需要处理的线程直接调用连接池执行线程。当插入的线程个数超过线程池个数的时候,就会排队等待。。。

    线程池不需要到别的地方找,JDK就自带有一个挺不错的池:java.util.concurrent.ExecutorService。

    下面是个线程池工具类。。

     1 package com.iafclub.jrrestServer.thread;
     2 
     3 import java.util.concurrent.ExecutorService;
     4 import java.util.concurrent.Executors;
     5 
     6 /**线程池
     7  * 
     8  * @author chenweixian
     9  *
    10  */
    11 public class ThreadPool{
    12     private static ThreadPool threadPool;
    13     // 线程池
    14     private ExecutorService executorService = null;
    15     
    16     private ThreadPool(){
    17         // 线程池加载10个线程
    18         executorService = Executors.newFixedThreadPool(10);
    19     }
    20     
    21     public static synchronized ThreadPool getInstance(){
    22         if (threadPool == null){
    23             threadPool = new ThreadPool();
    24         }
    25         return threadPool;
    26     }
    27     
    28     /**执行线程
    29      * 
    30      * @param thread
    31      */
    32     public void threadDo(Thread thread){
    33         executorService.submit(thread);
    34     }
    35     
    36 }
  • 相关阅读:
    五步轻松实现对现代浏览器的兼容
    本地存储—localStorage(HTML5)
    浏览器本地存储(browser-storage)
    behavior
    CodeForces
    Codeforces 982C(dfs+思维)
    Codeforces 982C(dfs+思维)
    P3370 【模板】字符串哈希
    codeforces 985E Pencils and Boxes(dp+思维)
    codeforces 985E Pencils and Boxes(dp+思维)
  • 原文地址:https://www.cnblogs.com/a393060727/p/5569028.html
Copyright © 2011-2022 走看看