`

一个线程池的实现

阅读更多
线程池使用背景:当有大批量的任务在一个时间段需要执行的时候,为了控制开辟的线程数量,节约资源,就应该考虑到线程池的使用。

由此想到的一个关于程序级别的性能调优问题,说到多线程这里,当有复杂而且耗时的任务需要处理的时候,首先应考虑到使用多线程进行并发处理,但当需要处理的任务数量特别多的情况下,又应该开始考虑到线程池的使用以控制开启的线程数量。

下面是一个线程池的具体实现:

import java.util.LinkedList;

import org.apache.log4j.Logger;




public class ThreadPoolMage {

/**
* 线程池中线程个数
*/
private final int nThreads;

/**
* 存放线程
*/
private final PoolWorker[] threads;

private static ThreadPoolMage  PoolObj = null;

/**
* 事件队列
*/
private final LinkedList queue;

public static ThreadPoolMage getInstance(int nThreads) {
    if (PoolObj==null){
    PoolObj = new ThreadPoolMage(nThreads);
    }
    return PoolObj ;
  }

private static final Logger logger = Logger
.getLogger(ThreadPoolMage.class);

/**
* 构造函数
*
* @param nThreads
*            线程个数
*/
private ThreadPoolMage(int nThreads) {

logger.info("ThreadPoolManager run");
this.nThreads = nThreads;
queue = new LinkedList();
if (System.getProperty("nthread")!=null){
try{
nThreads = Integer.parseInt(System.getProperty("nthread"));
}catch(Exception ex){

}
}

threads = new PoolWorker[nThreads];
logger.info("start the thread");
// 启动线程
for (int i = 0; i < nThreads; i++) {
logger.info("Start thread : " + i);
threads[i] = new PoolWorker(i);
threads[i].start();
}
}

/**
* 入队
*
* @param r
*            需要入队的事件,供外部调用,加入需要执行的任务
*/
public void execute(Runnable r) {
synchronized (queue) {
logger.info("add runnable into queue");
// 加入队列
queue.addLast(r);
// 通知正在阻塞的线程
queue.notify();
}
}

public void close() {
for (int i = 0; i < threads.length; i++) {
PoolWorker aWorker = threads[i];
aWorker.close();
}
synchronized (queue) {
queue.notifyAll();
}
}

/**
* <p>
* Title: PoolWorker
* </p>
* <p>
* Description: 线程池中的线程
* </p>
* <p>
*/

public class PoolWorker extends Thread {

private int threadNumber;

public PoolWorker(int threadNumber) {
this.threadNumber = threadNumber;
}

public int getThreadNumber() {
return threadNumber;
}

private boolean isFinished = false;

public void close() {
isFinished = true;
}

/**
* 线程运行函数
*/
public void run() {
// DebugPrint.printThreadDebug("PoolWork thread begin to run");
Runnable r;
while (!isFinished) {
synchronized (queue) {
// 如果队列为空,等
while (queue.isEmpty()) {
try {
/*
* DebugPrint .printThreadDebug("queue is empty,
* begin waiting");
*/
if(isFinished) {
return;
}
queue.wait();
} catch (InterruptedException ignored) {
// 捕到异常就忽略
/*
* DebugPrint .printThreadDebug("There is an
* exception, ignored it");
* DebugPrint.printException(ignored);
*/}
}
/*
* DebugPrint .printThreadDebug("Now queue isn't empty,
* begin running");
*/// 不空的时候,从队中取出一个事件
r = (Runnable) queue.removeFirst();
}
try {
// logger.info("begin to run the runnable");
// 执行这个事件
r.run();
Thread tt = new Thread();

} catch (Throwable e) {
// You might want to log something here
// 所有的异常全忽略
logger.error(
"there are a runtime exception in run the runable",
e);

}
}
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics