`
AutomaticThoughts
  • 浏览: 162344 次
社区版块
存档分类
最新评论

线程池

 
阅读更多

为什么要建立线程池?

 

在多线程项目中,如果建立的线程过多,反而可能导致运行速度大大减慢,这是由于线程建立所花费的时间和资源都比较多。
所以我们在多线程中必须很好地来管理线程, 在很好利用多线程能“同步工作”的好处之外,更有效地提高程序运行速度。

 

线程池是什么?

 

线程池是指具有固定数量的线程组成的一种组件。这些线程用来循环执行多个应用逻辑。

 

怎么建立线程池?

 

线程池主要包括4个部分,它们是:
1. 线程管理
 

主要是用来建立,启动,销毁工作线程和把工作任务加入工作线程。

 

2. 工作线程
 

它是真正的线程类,运行工作任务。

 

3. 工作队列
 

它是用来封装线程的容器。


4. 工作任务
 

它是实现应用逻辑的具体类。

 

流程图:

flow chart.

 

 线程管理类:

Java代码 复制代码 收藏代码
  1. <SPAN style="COLOR: #3366ff">import java.util.ArrayList;   
  2. import java.util.List;   
  3. import java.util.Queue;   
  4. import java.util.concurrent.ConcurrentLinkedQueue;   
  5.   
  6. /**  
  7.  * ThreadPoolManager.java  
  8.  *  
  9.  */  
  10.   
  11. /**  
  12.  * the thread pool manager, is responsible for starting and stopping the work thread.  
  13.  *   
  14.  * @author  gray  
  15.  * @version 1.0  
  16.  */  
  17. public class ThreadPoolManager {   
  18.   
  19.     private static final int DEFAULT_POOL_SIZE = 4;   
  20.     private List<WorkThread> threadPool;   
  21.     private Queue<Task> taskQueue;   
  22.     private int poolSize;   
  23.        
  24.     public ThreadPoolManager() {   
  25.         this(DEFAULT_POOL_SIZE);   
  26.     }   
  27.        
  28.     public ThreadPoolManager(int poolSize) {   
  29.         if(poolSize <= 0) {   
  30.             this.poolSize = DEFAULT_POOL_SIZE;   
  31.         }else {   
  32.             this.poolSize = poolSize;   
  33.         }   
  34.         threadPool = new ArrayList<WorkThread>(this.poolSize);   
  35.         taskQueue = new ConcurrentLinkedQueue<Task>();   
  36.         startup();   
  37.     }   
  38.        
  39.     public void startup() {   
  40.         System.out.println("start work thread...");   
  41.         synchronized(taskQueue) {   
  42.             for(int i = 0; i < this.poolSize; i++) {   
  43.                 WorkThread workThread = new WorkThread(taskQueue);   
  44.                 threadPool.add(workThread);   
  45.                 workThread.start();   
  46.             }   
  47.         }   
  48.     }   
  49.        
  50.     public void shutdown() {   
  51.         System.out.println("shutdown work thread...");   
  52.         synchronized(taskQueue) {   
  53.             for(int i = 0; i < this.poolSize; i++) {   
  54.                 threadPool.get(i).shutdown();   
  55.             }              
  56.                
  57.             System.out.println("done...");   
  58.         }   
  59.     }   
  60.        
  61.     public void addTask(Task task) {   
  62.         synchronized(taskQueue) {   
  63.             taskQueue.add(task);   
  64.             taskQueue.notify();   
  65.         }   
  66.     }   
  67. }</SPAN>  
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * ThreadPoolManager.java
 *
 */

/**
 * the thread pool manager, is responsible for starting and stopping the work thread.
 * 
 * @author  gray
 * @version 1.0
 */
public class ThreadPoolManager {

	private static final int DEFAULT_POOL_SIZE = 4;
	private List<WorkThread> threadPool;
	private Queue<Task> taskQueue;
	private int poolSize;
	
	public ThreadPoolManager() {
		this(DEFAULT_POOL_SIZE);
	}
	
	public ThreadPoolManager(int poolSize) {
		if(poolSize <= 0) {
			this.poolSize = DEFAULT_POOL_SIZE;
		}else {
			this.poolSize = poolSize;
		}
		threadPool = new ArrayList<WorkThread>(this.poolSize);
		taskQueue = new ConcurrentLinkedQueue<Task>();
		startup();
	}
	
	public void startup() {
		System.out.println("start work thread...");
		synchronized(taskQueue) {
			for(int i = 0; i < this.poolSize; i++) {
				WorkThread workThread = new WorkThread(taskQueue);
				threadPool.add(workThread);
				workThread.start();
			}
		}
	}
	
	public void shutdown() {
		System.out.println("shutdown work thread...");
		synchronized(taskQueue) {
			for(int i = 0; i < this.poolSize; i++) {
				threadPool.get(i).shutdown();
			}			
			
			System.out.println("done...");
		}
	}
	
	public void addTask(Task task) {
		synchronized(taskQueue) {
			taskQueue.add(task);
			taskQueue.notify();
		}
	}
}

 

工作线程类:

Java代码 复制代码 收藏代码
  1. <SPAN style="COLOR: #3366ff">import java.util.Queue;   
  2.   
  3. /**  
  4.  * WorkThread.java  
  5.  *  
  6.  */  
  7.   
  8. /**  
  9.  * the work thread used pull the task of task queue, and execute it.  
  10.  *   
  11.  * @author  gray  
  12.  * @version 1.0  
  13.  */  
  14. public class WorkThread extends Thread {   
  15.   
  16.     private boolean shutdown = false;   
  17.     private Queue<Task> queue;   
  18.        
  19.     public WorkThread(Queue<Task> queue) {   
  20.         this.queue = queue;   
  21.     }   
  22.        
  23.     public void run() {   
  24.         while(!shutdown) {   
  25.             try {   
  26.                 Thread.sleep(1000);   
  27.             } catch (InterruptedException e1) {   
  28.                 e1.printStackTrace();   
  29.             }   
  30.             System.out.println(Thread.currentThread() + " is running...");   
  31.             synchronized(queue) {   
  32.                 if(!queue.isEmpty()) {   
  33.                     Task task = queue.poll();   
  34.                     task.execute();   
  35.                 }else {   
  36.                     try {   
  37.                         queue.wait(1000);   
  38.                         System.out.println(Thread.currentThread() + " wait...");   
  39.                     }catch(InterruptedException e) {   
  40.                            
  41.                     }   
  42.                 }   
  43.             }   
  44.         }   
  45.     }   
  46.        
  47.     public void shutdown() {   
  48.         shutdown = true;   
  49.     }   
  50. }</SPAN>  
import java.util.Queue;

/**
 * WorkThread.java
 *
 */

/**
 * the work thread used pull the task of task queue, and execute it.
 * 
 * @author  gray
 * @version 1.0
 */
public class WorkThread extends Thread {

	private boolean shutdown = false;
	private Queue<Task> queue;
	
	public WorkThread(Queue<Task> queue) {
		this.queue = queue;
	}
	
	public void run() {
		while(!shutdown) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			System.out.println(Thread.currentThread() + " is running...");
			synchronized(queue) {
				if(!queue.isEmpty()) {
					Task task = queue.poll();
					task.execute();
				}else {
					try {
						queue.wait(1000);
						System.out.println(Thread.currentThread() + " wait...");
					}catch(InterruptedException e) {
						
					}
				}
			}
		}
	}
	
	public void shutdown() {
		shutdown = true;
	}
}

 

工作任务接口:

 

Java代码 复制代码 收藏代码
  1. <SPAN style="COLOR: #3366ff">/**  
  2.  * Task.java  
  3.  *  
  4.  */  
  5.   
  6. /**  
  7.  * The task want to execute.  
  8.  *   
  9.  * @author  gray  
  10.  * @version 1.0  
  11.  */  
  12. public interface Task {   
  13.   
  14.     public void execute();   
  15. }</SPAN>  
/**
 * Task.java
 *
 */

/**
 * The task want to execute.
 * 
 * @author  gray
 * @version 1.0
 */
public interface Task {

	public void execute();
}

 

工作任务类:

Java代码 复制代码 收藏代码
  1. <SPAN style="COLOR: #3366ff">/**  
  2.  * SimpleTask.java  
  3.  *  
  4.  */  
  5.   
  6. /**  
  7.  * @author  gray  
  8.  * @version 1.0  
  9.  */  
  10. public class SimpleTask implements Task {   
  11.   
  12.     /* (non-Javadoc)  
  13.      * @see Task#execute()  
  14.      */  
  15.     public void execute() {   
  16.         System.out.println(Thread.currentThread());   
  17.     }   
  18.   
  19. }</SPAN>  
/**
 * SimpleTask.java
 *
 */

/**
 * @author  gray
 * @version 1.0
 */
public class SimpleTask implements Task {

	/* (non-Javadoc)
	 * @see Task#execute()
	 */
	public void execute() {
		System.out.println(Thread.currentThread());
	}

}

 

线程池测试类:

Java代码 复制代码 收藏代码
  1. <SPAN style="COLOR: #3366ff">/**  
  2.  * ThreadPoolDemo.java  
  3.  *  
  4.  */  
  5.   
  6. /**  
  7.  * @author  gray  
  8.  * @version 1.0  
  9.  */  
  10. public class ThreadPoolDemo {   
  11.   
  12.     public static void main(String[] args) {   
  13.         ThreadPoolManager threadMg = new ThreadPoolManager();   
  14.            
  15.         for(int i = 0; i < 50; i++) {   
  16.             threadMg.addTask(new SimpleTask());   
  17.         }   
  18.         try {   
  19.             Thread.sleep(5000);   
  20.         } catch (InterruptedException e) {   
  21.             e.printStackTrace();   
  22.         }   
  23.         threadMg.shutdown();   
  24.     }      
  25. }</SPAN>  
分享到:
评论

相关推荐

    线程池线程池线程池线程池

    线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池线程池...

    java线程池概念.txt

    corePoolSize:核心池的大小,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中; ...

    阻塞线程池 阻塞线程池 阻塞线程池

    阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池阻塞线程池...

    Python 使用threading+Queue实现线程池示例

    一、线程池 1、为什么需要使用线程池 1.1 创建/销毁线程伴随着系统开销,过于频繁的创建/销毁线程,会很大程度上影响处理效率。 记创建线程消耗时间T1,执行任务消耗时间T2,销毁线程消耗时间T3,如果T1+T3&gt;T2,那...

    线程池  

    VC实现线程池

    易语言真正的线程池简易实现

    易语言简易线程池的实现。 ——V雪落有声V原创。转载请保留。前文:。为了能充分理解本篇文章的内容,需要了解的知识如下:。1.事件对象的使用:http://baike.baidu.com/view/751499.htm。2.信号量的使用:...

    Java简单线程池 线程池中文文档

    简单的线程池程序+中文文档 包结构: com.tangkai.threadpool --SimpleThread.java 工作线程 --TestThreadPool.java 程序入口 --ThreadPoolManager.java 线程池管理类

    Windows下一个比较完美的线程池实现和示例

    Windows下一个比较完美的线程池实现和示例 本线程池提供了如下功能: 1.能根据任务个数和当前线程的多少在最小/最大线程个数之间自动调整(Vista后的系统有 SetThreadpoolThreadMaximum 等函数有类似功能); 2.能方便...

    C#管理线程池的类ThreadManager

    C#管理线程池的类 /* How to use Thread Classs * * ============== * public ELMService() { InitializeComponent(); etm.ClalThreadPool("EmailThreads", (uint)ApplicationInfo.EmailParsingThreads); ...

    线程池.zip,互斥锁+条件变量+队列,实现线程池,包括线程池的创建,塞任务,和销毁线程池

    线程池

    易语言线程池操作例程(解决内存不断升高的问题)

     因为本人是个小白,多线程经常用,但是线程池并没有用过,(一听到线程池,总感觉高大上)。但是近期写彩票软件的时候发现,多线程长期操作会导致内容不断的升高直至报错,遂想起了线程池,完善后发现不是一般的叼...

    一个通用的Java线程池类

    2.然后根据提示运行java命令执行示例程序,观看线程池的运行结果 目标:Java中多线程技术是一个难点,但是也是一个核心技术。因为Java本身就是一个多线程语言。本人目前在给46班讲授Swing的网络编程--使用Swing来...

    VC简单的线程池使用实例

    1.线程池管理器(ThreadPoolManager):用于创建并管理线程池 2.工作线程(WorkThread): 线程池中线程 3.任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。 4.任务队列:用于存放没有处理的...

    如何使用线程池

    以下示例显示如何使用线程池。首先创建 ManualResetEvent 对象,此对象使程序能够知道线程池何时运行完所有的工作项。接着,尝试向线程池添加一个线程。如果添加成功,则添加其余的线程(本例中为 4 个)。然后...

    linux线程池创建c实现

    linux线程池创建c实现 linux线程池创建c实现 linux线程池创建c实现 linux线程池创建c实现 linux线程池创建c实现 linux线程池创建c实现

    windows线程池,使用Windows自带的线程池api功能,比你写的线程池性能好得多

    使用Windows自带的线程池功能,比你写的线程池性能好得多

    Linux下通用线程池的构建

    什么是线程池?简单点说,线程池就是有一堆已经创建好了的线程,初始它们都处于空闲等待状态,当有新的任务需要处理的时候,就从这个池子里面取一个空闲等待的线程来处理该任务,当处理完成了就再次把该线程放回池中...

    一个简单线程池的实现

    这是一个简单线程池的实现,虽然有很多bug,但是能够简单地实现线程池。

    Java 自己实现线程池

    Java开发,Android开发,自己实现线程池,明白线程池的实现机制

    jdbc线程池演示demo

    本实例采用c3p0作为线程池工具包,讲解了jdbc基本用法,同时给出了Oracle以及mysql增(单插入、批量插入)、删、查、改等功能,可以直接复制使用。

Global site tag (gtag.js) - Google Analytics