java线程池
线程池主要是用来 处理多个请求时,减少资源消耗,提高应用性能。
下面的代码是来自于 孙卫琴:<<Java网络编程精解>> 中线程池实现源码, 代码结构简单清晰,对于理解线程池,wait(),notify()方法都有有很好的帮助.
import java.util.LinkedList;
public class ThreadPool extends ThreadGroup {
private boolean isClosed = false; // 线程池是否关闭
private LinkedList<Runnable> workQueue; // 表示工作队列
private static int threadPoolID; // 表示线程池ID
private int threadID; // 表示工作线程ID
public ThreadPool(int poolSize) { // poolSize指定线程池中的工作线程数目
super("ThreadPool-" + (threadPoolID++));
setDaemon(true);
workQueue = new LinkedList<Runnable>(); // 创建工作队列
for (int i = 0; i < poolSize; i++)
new WorkThread().start(); // 创建并启动工作线程
}
/** 向工作队列中加入一个新任务,由工作线程去执行该任务 */
public synchronized void execute(Runnable task) {
if (isClosed) { // 线程池被关则抛出IllegalStateException异常
throw new IllegalStateException();
}
if (task != null) {
workQueue.add(task);
notify(); // 唤醒正在getTask()方法中等待任务的工作线程
}
}
/** 从工作队列中取出一个任务,工作线程会调用此方法 */
protected synchronized Runnable getTask() throws InterruptedException {
while (workQueue.size() == 0) {
if (isClosed) {
return null;
}
wait(); // 如果工作队列中没有任务,就等待任务
}
return workQueue.removeFirst();
}
/** 关闭线程池 */
public synchronized void close() {
if (!isClosed) {
isClosed = true;
workQueue.clear();
interrupt();
}
}
/** 等待工作线程把所有任务执行完 */
public void join() {
synchronized (this) {
isClosed = true;
notifyAll(); // 唤醒还在getTask()方法中等待任务的工作线程
}
Thread[] threads = new Thread[activeCount()];
// enumerate()方法继承自ThreadGroup类,获得线
相关文档:
Java NIO API详解
在JDK
1.4以前,Java的IO操作集中在java.io这个包中,是基于流的阻塞(blocking)API。对于大多数应用来说,这样的API使用很方
便,然而,一些对性能要求较高的应用,尤其是服务端应用,往往需要一个更为有效的方式来处理IO。从JDK 1.4起,NIO
API作为一个基于缓冲区,并能提供非阻塞(non-blo ......
package Demo;
// 受限泛型
class Info17<T> {
private T var; // 定义泛型变量
public void setVar(T var) {
this.var = var;
}
public T getVar() {
return this.var;
}
public String toString() { // 直接打印
return this.var.toString();
}
}
public class GenericsDemo17 {
publ ......
package Demo;
// 使用泛型统一传入的参数类型
class Info28<T> {
private T var; // 此类型由外部决定
public T getVar() {
return this.var;
}
public void setVar(T var) {
this.var = var;
}
public String toString() { // 覆写Object类中的toString()方法
return this.var.toString();
......
package Demo;
// Java泛型数组
public class GenericsDemo30 {
public static void main(String args[]) {
Integer i[] = fun1(1, 2, 3, 4, 5, 6); // 返回泛型数组
fun2(i);
}
public static <T> T[] fun1(T... arg) { // 接收可变参数
return arg; // 返回泛型数组
}
public static <T> ......