- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
public class ThreadPoolExecutor implements Executor {
private int maximumPoolSize; // ìàêñèìàëüíîå êîëè÷åñòâî ïîòîêîâ
private long keepAliveTime; // âðåìÿ îæèäàíèÿ íîâîé çàäà÷è
private Integer poolSize; // êîëè÷åñòâî ñîçäàííûõ ïîòîêîâ
private Vector workQueue; // î÷åðåäü çàäà÷
private Vector threadPool; // ïóë ïîòîêîâ
public ThreadPoolExecutor(int maxPoolSize, long time) {
this.maximumPoolSize = maxPoolSize;
this.keepAliveTime = time;
this.poolSize = new Integer(0);
workQueue = new Vector();
threadPool = new Vector();
new Thread() {
public void run() {
for (;;) {
try {
Thread.sleep(keepAliveTime);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
interruptIfIdle();
}
}
}.start();
}
public void execute(Runnable task) {
if (task == null)
throw new NullPointerException();
workQueue.addElement(task);
for (;;) {
int status = addIfUnderMaximumPoolSize(task);
if (status > 0)
return;
if (status == 0) {
reject(task);
return;
}
}
}
public void shutdown() {
if (threadPool.size() > 0)
for (int i=0; i < threadPool.size(); i++) {
((Thread) threadPool.elementAt(i)).interrupt();
}
}
public void reject(Runnable task) {
//
}
private int addIfUnderMaximumPoolSize(Runnable task) {
Thread t = null;
int status = 0;
synchronized (poolSize) {
if (poolSize.intValue() < maximumPoolSize) {
Runnable next = (Runnable) workQueue.elementAt(0);
workQueue.removeElementAt(0);
if (next == task) {
status = 1;
} else
status = -1;
t = addThread(next);
}
}
return status;
}
private Thread addThread(Runnable task) {
Thread thread = new Thread(task);
threadPool.addElement(thread);
thread.run();
poolSize = new Integer(poolSize.intValue()+1);
return new Thread();
}
private void interruptIfIdle() {
synchronized (threadPool) {
for (int i=0; i < threadPool.size(); i++) {
try {
((Thread) threadPool.elementAt(i)).interrupt();
} finally {
poolSize = new Integer(poolSize.intValue()-1);
}
}
}
}
}
Junior пишет весьма упрощенный ThreadPoolExecutor для BlackBerry (сорри, не тот пост кинул в прошлый раз).
Комментарии (0) RSS
Добавить комментарий