📄 threadpool.java
字号:
/*
* Copyright (C) 2006-2007 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.funambol.util;
/**
* A default implementation of a ThreadPool
* built with a maximum number of live threads.
*/
public class ThreadPool implements Runnable {
protected Queue queue;
protected boolean stopped = false;
protected final ThreadPoolMonitor monitor;
public ThreadPool(ThreadPoolMonitor monitor, int numberOfThreads) {
this.monitor = monitor;
queue = new Queue();
for ( int i = 0; i < numberOfThreads; i++ ) {
startThread();
}
}
public ThreadPool(int numberOfThreads) {
this(new ThreadPoolMonitor(), numberOfThreads);
}
/** Start a new thread running */
public Thread startThread() {
Thread thread = new Thread( this );
thread.start();
return thread;
}
public void stop() {
stopped = true;
}
/**
* Returns number of runnable object in the queue.
*/
public int getRunnableCount() {
return queue.size();
}
/**
* Dispatch a new task in the pool to be invoked asynchronously
* later if possible
*/
public void startThread(Runnable task) {
queue.add( task );
}
/** The method run by the pool of background threads
*/
public void run() {
while ( ! stopped ) {
Runnable task = (Runnable) queue.remove();
if ( task != null ) {
try {
Thread tr = new Thread(task);
tr.setPriority(Thread.MIN_PRIORITY);
tr.run();
tr = null;
} catch (Throwable t) {
Log.error(this, "throwable catched in run()");
monitor.handleThrowable(this.getClass(), task, t);
} finally {
task = null;
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -