Здравствуйте, Selavi, Вы писали:
S>Заранее спасибо за потраченное время.
Привет. Реализацию не смотрел, просто решил выполнить задание на java (мой родной язык). Получилось так:
package net.sf.brunneng;
import java.util.*;
public class ThreadPool {
private class ClientTask {
final int clientId;
final Runnable runnable;
public ClientTask(int clientId, Runnable runnable) {
this.clientId = clientId;
this.runnable = runnable;
}
}
private boolean closed;
private final List<ClientTask> tasks = Collections.synchronizedList(new ArrayList<ClientTask>());
private List<Thread> threads = new ArrayList<Thread>();
private Set<Integer> executingClients = Collections.synchronizedSet(new HashSet<Integer>());
public List<ClientTask> getTasks() {
return tasks;
}
public ThreadPool(int threadsCount) {
for (int i = 0; i < threadsCount; ++i) {
Thread thread = createThread();
threads.add(thread);
thread.start();
}
}
private ClientTask getNextClientTask() {
ClientTask res = null;
synchronized (tasks) {
for (int i = 0; i < tasks.size(); i++) {
ClientTask task = tasks.get(i);
if (!executingClients.contains(task.clientId)) {
res = task;
executingClients.add(task.clientId);
tasks.remove(i);
break;
}
}
}
return res;
}
private Thread createThread() {
return new Thread(new Runnable() {
@Override
public void run() {
boolean finish = false;
while (!finish && !closed) {
try {
ClientTask task = getNextClientTask();
if (task == null) {
synchronized (tasks) {
tasks.wait();
}
continue;
}
task.runnable.run();
executingClients.remove(task.clientId);
} catch (InterruptedException e) {
e.printStackTrace();
finish = true;
}
}
}
});
}
public void addTask(int clientId, Runnable task) {
tasks.add(new ClientTask(clientId, task));
if (!executingClients.contains(clientId)) {
synchronized (tasks) {
tasks.notify();
}
}
}
public void close() {
closed = true;
synchronized (tasks) {
tasks.notifyAll();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException ignored) {
}
}
}
}
Если кто шарит в java, прошу поревьювить. Я сам с ручной многопоточностью редко работал, так что могут быть косяки..