线程池

为什么要建立线程池?

 

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

 

线程池是什么?

 

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

 

怎么建立线程池?

 

线程池主要包括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>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值