1

我正在为黑莓开发一个java线程池,这是我目前拥有的代码:

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
...
4

1 回答 1

2

您正在r.run()队列同步语句中执行您的作业(即),因此,直到每个线程完成它的作业后才会释放队列锁。您应该在同步语句之外执行作业。试试看。

于 2013-02-25T19:34:41.667 回答