我正在java中为blackberry开发一个线程池,这是我目前的代码:
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();
}
}
}
问题在于,如果我排队10个作业,它们将一个接一个地执行,而不是同时执行,例如:
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();
}
}
});
}
我得到了:
I'm work 1
I'm work 2
I'm work 3
...
答案 0 :(得分:2)
您正在队列synchronized语句中执行您的作业(即r.run()
),因此,在每个线程完成它的作业之前,队列锁定不会被释放。您应该在synchronized语句之外执行作业。试试吧。