利用可能なワーカースレッドがプールサイズと同じである単純なスレッドプールを作成します。使用可能なスレッドが存在するかどうかを確認してから、ロックを待機します。
また、acquire()が値を取得するまでブロックするセマフォも使用できます。 セマフォexanple:シンプルなスレッドプールの
Semaphore semaphore = new Semaphore(pool_size);
//critical section
semaphore.acquire();
...
semaphore.release();
例:
private List<WorkerThread> workers;
private LinkedList<WorkerThread> availWorkers = new LinkedList<WorkerThread>();
private LinkedList<WorkerThread> busyWorkers = new LinkedList<WorkerThread>();
は方法
public boolean submit(Runnable runnable) {
if (runnable == null) {
return false;
}
synchronized (Lock) {
handoffPending = true;
// Wait until a worker thread is available
while ((availWorkers.size() < 1) && !isShutdown) {
try {
Lock.wait(500);
} catch (InterruptedException ignore) {
}
}
if (!isShutdown) {
WorkerThread wt = (WorkerThread)availWorkers.removeFirst();
busyWorkers.add(wt);
wt.run(runnable);
} else {
// If the thread pool is going down, execute the Runnable
// within a new additional worker thread (no thread from the pool).
WorkerThread wt = new WorkerThread(this, threadGroup,
"WorkerThread-LastJob", prio, isMakeThreadsDaemons(), runnable);
busyWorkers.add(wt);
workers.add(wt);
wt.start();
}
Lock.notifyAll();
}
return true;
}
を提出**は、それがメインスレッド(つまり、これらのタスクを提出している)を持つことが可能です一時停止スレッドプール内のスレッドが利用可能になるまで**実際には誰もコードなしで何かを言うことさえできませんか? – ShayHaned