线程池
来源:互联网 发布:linux 全站 备份 编辑:程序博客网 时间:2024/05/19 20:23
在应用中,我们常常需要Thread缓冲池来做一些事以提高程序的效率和并发性。本文演示了如何利用Queue这种数据结构实现一个简单的Thread缓冲池。
public class SyncQueue {
public SyncQueue(int size) {
_array = new Object[size];
_size = size;
_oldest = 0;
_next = 0;
}
public synchronized void put(Object o) {
while (full()) {
try {
wait();
} catch (InterruptedException ex) {
throw new ExceptionAdapter(ex);
}
}
_array[_next] = o;
_next = (_next + 1) % _size;
notify();
}
public synchronized Object get() {
while (empty()) {
try {
wait();
} catch (InterruptedException ex) {
throw new ExceptionAdapter(ex);
}
}
Object ret = _array[_oldest];
_oldest = (_oldest + 1) % _size;
notify();
return ret;
}
protected boolean empty() {
return _next == _oldest;
}
protected boolean full() {
return (_next + 1) % _size == _oldest;
}
protected Object [] _array;
protected int _next;
protected int _oldest;
protected int _size;
}
在以上代码中使用了ExceptionAdapter这个类,它的作用是把一个checkedException包装成RuntimeException。详细的说明可以参考我的避免在Java中使用CheckedException一文。
接下来我们需要一个对象来表现Thread缓冲池所要执行的任务。可以发现JDK中的Runnableinterface非常合适这个角色。
最后,剩下工作线程的实现就很简单了:从SyncQueue里取出一个Runnable对象并执行它。
public class Worker implements Runnable {
public Worker(SyncQueue queue) {
_queue = queue;
}
public void run() {
while (true) {
Runnable task = (Runnable) _queue.get();
task.run();
}
}
protected SyncQueue _queue = null;
}
下面是一个使用这个Thread缓冲池的例子:
//构造Thread缓冲池
SyncQueue queue = new SyncQueue(10);
for (int i = 0; i < 5; i ++) {
new Thread(new Worker(queue)).start();
}
//使用Thread缓冲池
Runnable task = new MyTask();
queue.put(task);
为了使本文中的代码尽可能简单,这个Thread缓冲池的实现是一个基本的框架。当使用到实际中时,一些其他功能也可以在这一基础上添加,比如异常处理,动态调整缓冲池大小等等。
- 线程与线程池
- 线程池 线程优先级
- Executor线程,线程池
- 线程、多线程、线程池
- IOS-线程、线程池
- Java线程:线程池
- 线程和线程池
- 线程、多线程、线程池
- 线程、多线程、线程池
- 线程(六)线程池
- ExecutorService(线程池)+线程
- 线程和线程池
- 线程&线程池 简略
- 线程和线程池
- 线程池 线程锁
- 线程、线程池总结
- 线程与线程池
- 线程、锁、线程池
- 二分图匹配
- 最大流增广路算法
- 深度优先搜索
- 深度优先搜索和广度优先搜索(1)
- 深度优先搜索和广度优先搜索(2)
- 线程池
- 差分约束系统
- 数据库知识
- 数据库面试
- javabean传值
- oracle常用知识
- 算法面试题(1)
- 算法面试题(2)
- 算法面试题(3)