建立自己的JAVA线程池

建立自己的JAVA线程池

为什么要建立线程池?

 

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

 

线程池是什么?

 

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

 

怎么建立线程池?

 

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

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

 

2. 工作线程
 

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

 

3. 工作队列
 

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


4. 工作任务
 

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

 

 线程管理类:

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.  * Copyright (C)  2008 State Street Corporation. All Rights Reserved.  
  10.  *  
  11.  */  
  12.   
  13. /**  
  14.  * the thread pool manager, is responsible for starting and stopping the work thread.  
  15.  *   
  16.  * @author  e458487  
  17.  * @version 1.0  
  18.  */  
  19. public class ThreadPoolManager {   
  20.   
  21.     private static final int DEFAULT_POOL_SIZE = 4;   
  22.     private List<WorkThread> threadPool;   
  23.     private Queue<Task> taskQueue;   
  24.     private int poolSize;   
  25.        
  26.     public ThreadPoolManager() {   
  27.         this(DEFAULT_POOL_SIZE);   
  28.     }   
  29.        
  30.     public ThreadPoolManager(int poolSize) {   
  31.         if(poolSize <= 0) {   
  32.             this.poolSize = DEFAULT_POOL_SIZE;   
  33.         }else {   
  34.             this.poolSize = poolSize;   
  35.         }   
  36.         threadPool = new ArrayList<WorkThread>(this.poolSize);   
  37.         taskQueue = new ConcurrentLinkedQueue<Task>();   
  38.         startup();   
  39.     }   
  40.        
  41.     public void startup() {   
  42.         System.out.println("start work thread...");   
  43.         synchronized(taskQueue) {   
  44.             for(int i = 0; i < this.poolSize; i++) {   
  45.                 WorkThread workThread = new WorkThread(taskQueue);   
  46.                 threadPool.add(workThread);   
  47.                 workThread.start();   
  48.             }   
  49.         }   
  50.     }   
  51.        
  52.     public void shutdown() {   
  53.         System.out.println("shutdown work thread...");   
  54.         synchronized(taskQueue) {   
  55.             for(int i = 0; i < this.poolSize; i++) {   
  56.                 threadPool.get(i).shutdown();   
  57.             }              
  58.                
  59.             System.out.println("done...");   
  60.         }   
  61.     }   
  62.        
  63.     public void addTask(Task task) {   
  64.         synchronized(taskQueue) {   
  65.             taskQueue.add(task);   
  66.             taskQueue.notify();   
  67.         }   
  68.     }   
  69. }</SPAN>  
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* ThreadPoolManager.java
*
* Copyright (C)  2008 State Street Corporation. All Rights Reserved.
*
*/
/**
* the thread pool manager, is responsible for starting and stopping the work thread.
*
* @author  e458487
* @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.  * Copyright (C)  2008 State Street Corporation. All Rights Reserved.  
  7.  *  
  8.  */  
  9.   
  10. /**  
  11.  * the work thread used pull the task of task queue, and execute it.  
  12.  *   
  13.  * @author  e458487  
  14.  * @version 1.0  
  15.  */  
  16. public class WorkThread extends Thread {   
  17.   
  18.     private boolean shutdown = false;   
  19.     private Queue<Task> queue;   
  20.        
  21.     public WorkThread(Queue<Task> queue) {   
  22.         this.queue = queue;   
  23.     }   
  24.        
  25.     public void run() {   
  26.         while(!shutdown) {   
  27.             try {   
  28.                 Thread.sleep(1000);   
  29.             } catch (InterruptedException e1) {   
  30.                 e1.printStackTrace();   
  31.             }   
  32.             System.out.println(Thread.currentThread() + " is running...");   
  33.             synchronized(queue) {   
  34.                 if(!queue.isEmpty()) {   
  35.                     Task task = queue.poll();   
  36.                     task.execute();   
  37.                 }else {   
  38.                     try {   
  39.                         queue.wait(1000);   
  40.                         System.out.println(Thread.currentThread() + " wait...");   
  41.                     }catch(InterruptedException e) {   
  42.                            
  43.                     }   
  44.                 }   
  45.             }   
  46.         }   
  47.     }   
  48.        
  49.     public void shutdown() {   
  50.         shutdown = true;   
  51.     }   
  52. }</SPAN>  
import java.util.Queue;
/**
* WorkThread.java
*
* Copyright (C)  2008 State Street Corporation. All Rights Reserved.
*
*/
/**
* the work thread used pull the task of task queue, and execute it.
*
* @author  e458487
* @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.  * Copyright (C)  2008 State Street Corporation. All Rights Reserved.  
  5.  *  
  6.  */  
  7.   
  8. /**  
  9.  * The task want to execute.  
  10.  *   
  11.  * @author  e458487  
  12.  * @version 1.0  
  13.  */  
  14. public interface Task {   
  15.   
  16.     public void execute();   
  17. }</SPAN>  
/**
* Task.java
*
* Copyright (C)  2008 State Street Corporation. All Rights Reserved.
*
*/
/**
* The task want to execute.
*
* @author  e458487
* @version 1.0
*/
public interface Task {
public void execute();
}

 

工作任务类:

Java代码 复制代码
  1. <SPAN style="COLOR: #3366ff">/**  
  2.  * SimpleTask.java  
  3.  *  
  4.  * Copyright (C)  2008 State Street Corporation. All Rights Reserved.  
  5.  *  
  6.  */  
  7.   
  8. /**  
  9.  * @author  e458487  
  10.  * @version 1.0  
  11.  */  
  12. public class SimpleTask implements Task {   
  13.   
  14.     /* (non-Javadoc)  
  15.      * @see Task#execute()  
  16.      */  
  17.     public void execute() {   
  18.         System.out.println(Thread.currentThread());   
  19.     }   
  20.   
  21. }</SPAN>  
/**
* SimpleTask.java
*
* Copyright (C)  2008 State Street Corporation. All Rights Reserved.
*
*/
/**
* @author  e458487
* @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.  * Copyright (C)  2008 State Street Corporation. All Rights Reserved.  
  5.  *  
  6.  */  
  7.   
  8. /**  
  9.  * @author  e458487  
  10.  * @version 1.0  
  11.  */  
  12. public class ThreadPoolDemo {   
  13.   
  14.     public static void main(String[] args) {   
  15.         ThreadPoolManager threadMg = new ThreadPoolManager();   
  16.            
  17.         for(int i = 0; i < 50; i++) {   
  18.             threadMg.addTask(new SimpleTask());   
  19.         }   
  20.         try {   
  21.             Thread.sleep(5000);   
  22.         } catch (InterruptedException e) {   
  23.             e.printStackTrace();   
  24.         }   
  25.         threadMg.shutdown();   
  26.     }      
  27. }</SPAN>  

http://www.javaeye.com/topic/387566

你可能感兴趣的:(建立自己的JAVA线程池)