我们大家都知道,在处理多线程服务并发时,由于创建线程需要占用很多的系统资源,所以为了避免这些不必要的损耗,通常我们采用线程池来解决这些问题。

线程池的基本原理是,首先创建并保持一定数量的线程,当需要使用线程时,我们从池中取得线程,再将需要运行的任务交给线程进行处理,当任务完成后再将其释放回池中。

下面,我给出一个很简单的实现模型,仅供参考。

ThreadPool.java

package org.loon.framework.util.test;

import java.util.LinkedList;

import java.util.List;

public class ThreadPool ... {

private static ThreadPool instance = null ;

// 优先级低

public static final int PRIORITY_LOW = 0 ;

// 普通

public static final int PRIORITY_NORMAL = 1 ;

// 高

public static final int PRIORITY_HIGH = 2 ;

// 用以保存空闲连接

private List[] _idxThreads;

// 关闭

private boolean _shutdown = false ;

// 线程数量

private int _threadCount = 0 ;

// debug信息是否输出

private boolean _debug = false ;

/** */ /**

* 返回ThreadPool实例

*

* @return

*/

public static ThreadPool getInstance() ... {

if (instance == null ) ... {

instance = new ThreadPool();

}

return instance;

}

// 初始化线程list

private ThreadPool() ... {

this ._idxThreads = new List[] ... { new LinkedList(), new LinkedList(),

new LinkedList() } ;

this ._threadCount = 0 ;

}

/** */ /**

* 同步方法,完成任务后将资源放回线程池中

* @param repool

*/

protected synchronized void repool(Pooled repool) ... {

if ( this ._shutdown) ... {

if ( this ._debug) ... {

System.out.println( " ThreadPool.repool():重设中…… " );

}

// 优先级别判定

switch (repool.getPriority()) ... {

case Thread.MIN_PRIORITY:

this ._idxThreads[PRIORITY_LOW].add(repool);

break ;

case Thread.NORM_PRIORITY:

this ._idxThreads[PRIORITY_NORMAL].add(repool);

break ;

case Thread.MAX_PRIORITY:

this ._idxThreads[PRIORITY_HIGH].add(repool);

break ;

default :

throw new IllegalStateException( " 没有此种级别 " );

}

// 通知所有线程

notifyAll();

} else ... {

if ( this ._debug) ... {

System.out.println( " ThreadPool.repool():注销中…… " );

}

repool.shutDown();

}

if ( this ._debug) ... {

System.out.println( " ThreadPool.repool():完成 " );

}

}

public void setDebug( boolean debug) ... {

this ._debug = debug;

}

public synchronized void shutDown() ... {

this ._shutdown = true ;

if ( this ._debug) ... {

System.out.println( " ThreadPool.shutDown():关闭中…… " );

}

for ( int index = 0 ;index <= PRIORITY_NORMAL;index ++ ) ... {

List threads = this ._idxThreads[index];

for ( int threadIndex = 0 ;threadIndex < threads.size();threadIndex ++ ) ... {

Pooled idleThread = (Pooled)threads.get(threadIndex);

idleThread.shutDown();

}

}

notifyAll();

}

/** */ /**

* 以指定的优先级启动线程

* @param target

* @param priority

*/

public synchronized void start(Runnable target, int priority) ... {

Pooled thread = null ;

List idleList = this ._idxThreads[priority];

int idleSize = idleList.size();

if (idleSize > 0 ) ... {

int lastIndex = idleSize - 1 ;

thread = (Pooled)idleList.get(lastIndex);

idleList.remove(idleList);

thread.setTarget(target);

} else ... {

this ._threadCount ++ ;

thread = new Pooled(target, " Pooled-> " + this ._threadCount, this );

switch (priority) ... {

case PRIORITY_LOW:

thread.setPriority(Thread.MIN_PRIORITY);

break ;

case PRIORITY_NORMAL:

thread.setPriority(Thread.NORM_PRIORITY);

break ;

case PRIORITY_HIGH:

thread.setPriority(Thread.MAX_PRIORITY);

break ;

default :

thread.setPriority(Thread.NORM_PRIORITY);

}

// 启动

thread.start();

}

}

/** */ /**

* 返回线程数量

*

* @return

*/

public int getThreadsCount() ... {

return this ._threadCount;

}

}

Pooled.java:

package org.loon.framework.util.test;

public class Pooled extends Thread ... {

private ThreadPool _pool;

private Runnable _target;

private boolean _shutdown = false ;

private boolean _idle = false ;

public Pooled(Runnable target) ... {

super (target);

}

public Pooled(Runnable target, String name) ... {

super (target, name);

}

public Pooled(Runnable target, String name, ThreadPool pool) ... {

super (name);

this ._pool = pool;

this ._target = target;

}

public Pooled(String name) ... {

super (name);

}

public Pooled(ThreadGroup group, Runnable target) ... {

super (group, target);

}

public Pooled(ThreadGroup group, Runnable target, String name) ... {

super (group, target, name);

}

public Pooled(ThreadGroup group, String name) ... {

super (group, name);

}

public Runnable getTarget() ... {

return this ._target;

}

public boolean isIdle() ... {

return this ._idle;

}

public void run() ... {

while ( ! this ._shutdown) ... {

this ._idle = false ;

if ( this ._target != null ) ... {

this ._target.run();

}

this ._idle = true ;

try ... {

this ._pool.repool( this );

synchronized ( this ) ... {

wait();

}

} catch (InterruptedException ex) ... {

System.err.println(ex.getMessage());

}

this ._idle = false ;

}

}

public synchronized void setTarget(Runnable target) ... {

this ._target = target;

notifyAll();

}

public synchronized void shutDown() ... {

this ._shutdown = true ;

notifyAll();

}

}

测试用类:

package org.loon.framework.util.test;

public class ThreadPoolTest ... {

private static Runnable createRunnable( final int id) ... {

return new Runnable() ... {

public void run() ... {

System.out.println( " 线程 " + id + " ,运行 " );

try ... {

Thread.sleep( 1000 );

}

catch (InterruptedException ex) ... { }

System.out.println( " 线程 " + id + " ,结束 " );

}

} ;

}

public static void main(String[]args) ... {

ThreadPool pool = ThreadPool.getInstance();

pool.setDebug( true );

for ( int i = 1 ; i <= 10 ; i ++ ) ... {

// 根据数值,设定不同优先级

if (i % 2 == 0 ) ... {

pool.start(createRunnable(i), ThreadPool.PRIORITY_HIGH);

} else ... {

pool.start(createRunnable(i), ThreadPool.PRIORITY_LOW);

}

}

System.out.println( " 线程池测试中…… " );

System.out.println( " 线程池线程总数: " + pool.getThreadsCount());

pool.shutDown();

}

}

标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,尊重他人劳动成果

文章转载自:网络转载

0

好文不易,鼓励一下吧!

java线程池 的方法_JAVA线程池的实现方法相关推荐

  1. java set和get原理_Java线程池的实现原理和使用

    为什么用线程池 在我们进行开发的时候,为了充分利用系统资源,我们通常会进行多线程开发,实现起来非常简单,需要使用线程的时候就去创建一个线程(继承Thread类.实现Runnable接口.使用Calla ...

  2. java 线程池 源码_java线程池源码分析

    我们在关闭线程池的时候会使用shutdown()和shutdownNow(),那么问题来了: 这两个方法又什么区别呢? 他们背后的原理是什么呢? 线程池中线程超过了coresize后会怎么操作呢? 为 ...

  3. java 线程池的理解_JAVA线程池原理的理解

    线程池原理基础理解: 线程池初始化规定个数的线程,然后这些线程一直运行,并且监控线程队列,只要线程队列被添加进线程,那么线程池不断从队列中取出线程运行.直到队列中的线程为空.实例代码如下: packa ...

  4. java线程池拒绝策略_Java线程池ThreadPoolExecutor的4种拒绝策略

    最近在做大批量数据采集转换工作,基础数据在本地但是需要调用网络资源完成数据转换.多方面原因在保证良好运行情况下,最多开5个线程进行网络资源调用.方案是基础数据在数据库分页,循环遍历每一条数据,创建调用 ...

  5. java线程池的应用_Java线程池的使用

    Java并发编程:线程池的使用 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了, ...

  6. java 队列占用内存大小_Java线程池队列吃的太饱,撑着了咋整?java 队列过大导致内存溢出...

    Java的Executors框架提供的定长线程池内部默认使用LinkedBlockingQueue作为任务的容器,这个队列是没有限定大小的,可以无限向里面submit任务. 当线程池处理的太慢的时候, ...

  7. java线程池多线程优先级_Java线程优先级

    java线程池多线程优先级 Priority of a thread describes how early it gets execution and selected by the thread ...

  8. java线程池存在时间_Java线程池基础

    目录: 一.线程池概述 1.线程池类 目前线程池类一般有两个,一个来自于Spring,一个来自于JDK: 来自Spring的线程池:org.springframework.scheduling.con ...

  9. java 线程池 资源回收_JAVA线程池资源回收的问题

    最近项目中为了提高用户体验度,前台创建任务后台任务,用多线程来跑. 现在的场景:后台定时任务管理这两个线程池,一个最大线程数10个,一个最大线程数15.应用部署之后,不超过5个小时,服务器负载高,内存 ...

最新文章

  1. js 使用 Lawnchair 存储 json 对象到本地
  2. Nature子刊:吃得越少,活得越久
  3. [转]Python测试框架对比----unittest, pytest, nose, robot framework对比
  4. pku 1486 求出二分匹配图中的必须边
  5. 分式求和python_python实现利用留数定理分解分式多项式
  6. 三数之和—leetcode15
  7. apple组织名称是什么_什么是Apple Macintosh?
  8. Spring Boot Shiro权限管理--自定义 FormAuthenticationFilter验证码整合
  9. [Java] 蓝桥杯PREV-8 历届试题 买不到的数目
  10. 漏洞payload 靶机_hackme:2 靶机攻略
  11. [转载] python 中numpy快速去除nan, inf的方法
  12. Qt5学习笔记之计时器
  13. 地图标识符号大全_资源小结:旅游类地图汇总(8.17版)
  14. 如何用银灿IS903主控DIY自己的U盘?(练习BGA焊接的好项目)
  15. 计算机网络的定义及答案,计算机网络习题库
  16. 你一生要知道的74幅世界名画…
  17. less06 引入(importing)
  18. Delta RPMs disabled because /usr/bin/applydeltarpm not installed
  19. ubuntu 下安装java_Ubuntu下安装java
  20. 推荐 -- 《分布式系统的工程化开发方法》

热门文章

  1. python messagebox弹窗退出_python 中messagebox使用 做中断调试不错
  2. python中的switch语句_python技巧 switch case语句
  3. 人类一败涂地电脑版_iOS账号分享 |人类一败涂地 我们继续相爱相杀,PC大火游戏移植!...
  4. 无法检测或故障_大众朗境挡位偶发缺失且无法启动
  5. 面试被问mysql扩展性设计相关的点,你知道该如何回答吗
  6. 用sum函数求三个数和C语言,C语言用函数写两数之和.doc
  7. zynq的emio和axi_【ZYNQ7000学习之旅 - 01】EMIO练习
  8. 家人不支持自己学计算机,家人不支持我学习,感觉父母对我好像是很无所谓的?...
  9. php 上传excel到mysql_PHP上传Excel文件导入数据到MySQL数据库示例
  10. mysql 交换空间_MySQL优化纪录