zoukankan      html  css  js  c++  java
  • 线程池及其实现

    进程,线程是现代操作系统两个比较重要的概念。正是由于它们的存在,使得程序和并发执行得了实现。
    通常,创建一个线程的代价远远小于创建一个进程,所以多线程是编写并发程序的首要选择。
    然而,即使有多线程,当线程数量太大时,不断的创建线程也会影响系统的性能,这时,我们可以创建
    线程池来达到重用线程的目的,从而尽可能有减小开消,从而大大提高系统性能,比如在网络爬虫heritrix
    中就使用了线程池。

    以下是一个简单线程池的实现(java程序)。

    本程序由4个类构成,TestThreadPool,用来测试的类,用来模拟客户端的请求。它会创建20个任务(Task),交给线程
    池(ThreadPoolManager)处理。线程池默认维护10个线程,当客户请求一个任务时,它会获取一个空闲线程,然后
    处理交给该线程(SimpleThread)处理。

    测试线程池的类(TestThreadPool)

    Code

    线程池类(TheadPool)

    Code

    线程类(SimpleThread)

    Code

    任务类(Task)

    Code

    运行结果如下:

    thread 0 starting
    thread 1 starting
    thread 2 starting
    thread 3 starting
    thread 4 starting
    thread 5 starting
    thread 6 starting
    thread 7 starting
    thread 8 starting
    thread 9 starting
    thread pool created
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    没有空闲线程!
    processing task1
    processing task3
    processing task5
    processing task7
    processing task9
    processing task0
    processing task2
    processing task4
    processing task6
    processing task8
    task1 processed
    task9 processed
    task5 processed
    task7 processed
    task3 processed
    task6 processed
    task4 processed
    task2 processed
    task0 processed
    task8 processed

  • 相关阅读:
    最短路径问题大总结(提纲)
    单源最短路——Bellman-Ford算法
    多源最短路——Floyd算法
    Bracket Sequences Concatenation Problem括号序列拼接问题(栈+map+思维)
    数位DP
    C++ string中的find()函数
    Planning The Expedition(暴力枚举+map迭代器)
    8月5号团队赛补题
    8月3号水题走一波-个人赛五
    Walking Between Houses(贪心+思维)
  • 原文地址:https://www.cnblogs.com/hustcat/p/1308425.html
Copyright © 2011-2022 走看看