Reputation: 1138
I'm developing a thread pool in java for blackberry, this is the code I currently have:
public class ThreadPool {
int maxWorkers = 15;
Vector queue = new Vector();
Thread[] workers;
public ThreadPool(int maxThreads) {
if (maxThreads <= maxWorkers)
maxWorkers = maxThreads;
workers = new Thread[maxThreads];
for (int i = 0; i < maxThreads; i++) {
// Crea un worker que ejecuta trabajos.
workers[i] = new Thread(new Runnable() {
public void run() {
Runnable r;
while (true) {
synchronized (queue) {
while (queue.size() == 0) {
try {
queue.wait();
} catch (Exception e) {
System.out.println("Error while waiting");
}
}
try {
r = (Runnable) queue.firstElement();
queue.removeElement(r);
r.run();
queue.notify();
} catch (Throwable e) {
System.out.println("nope!");
}
}
}
}
});
workers[i].start();
}
}
public void addWork(Runnable work) {
synchronized (queue) {
queue.addElement(work);
queue.notify();
}
}
}
The problem is that if I queue 10 jobs, they will execute one after another, not in a concurrently way, for instance:
for (int i=0; i<10; i++) {
pool.addWork(new Runnable() {
public void run() {
Random random = new Random();
int time = random.nextInt(5) * 1000;
System.out.println("I'm work " + i);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
And I get:
I'm work 1
I'm work 2
I'm work 3
...
Upvotes: 1
Views: 189
Reputation: 254
You are executing your job (i.e. r.run()
) inside the queue synchronized statement, therefore, the queue lock isn't released until after each thread completes it's job. You should execute the job outside the synchronized statement. Try that.
Upvotes: 2