多线程 - 分配工作

时间:2016-09-04 18:32:08

标签: java multithreading threadpool

在循环中创建和使用线程的正确方法是什么?

如果我想处理一百万件物品,我会创建一个循环来做到这一点。因此,为了提高效率,我将使其成为多线程并将每个项目分配给一个线程。让我们说我创建五个线程来处理这个问题。如何将工作分配给线程?

如果一个线程有一个较小的项目要处理,那么它可以自由地处理另一个 - 如何将循环中的下一个项目分配给该线程?

我是否在循环外创建线程,然后在其中使用它们?

以下是我正在研究的一个例子 - 它错过了使用对象的创建,只使用了两个线程,但我认为这里的人很聪明,知道我的意思:)

public class App 
{
    public static void main( String[] args )
    {
        App a = new App();
        a.doTest();
    }

    private void doTest() {
        Count c = new Count(21);
        Count c2 = new Count(7);
        Thread t = new Thread(c);
        Thread t2 = new Thread(c2);
        t.start();
        t2.start();
        for (int f = 0; f < 10; f++) {
                //here - how do I select which thread to send the work to?
                // ?????.processThis(nextObject);          //how do I send this to the right thread (one that is idle or has least work?)
        }

    }

    public class Count implements Runnable {

        private int count;

        public void processThis(Object someItemToProcess) {
            //here I'll set the object to process and call the method to process it    
        }

        public Count(int count) {
            this.count = count;
        }

        @Override
        public void run() {


            //for illustration purposes
//            for (int i = 1; i < count; i++) {
//                System.out.println("Thread " + Thread.currentThread().getId()  + " Count = " + i);
//            }

        }
    }
}

1 个答案:

答案 0 :(得分:5)

这些问题通常通过线程池解决,您可以向其提供任务并等待完成。在Java中,有几个线程池的实现,你可以用一个固定大小的学习开始学习:

// Create a thread pool
ExecutorService executor = Executors.newFixedThreadPool(threadsCount);

// Submit your tasks to the pool:
for (Count c: myCounts) {
    executor.submit(c);
}

// Shutdown the pool when you don't need it
executor.shutdown();

池将并行处理您的任务。如果您需要控制任务的执行,等待它们的完成,取消它们,获取它们的工作结果等,只需使用Future方法返回的submit()个对象。只要你需要,你就可以使用游泳池,但是当你不再需要它时别忘了把它关闭。

详细了解各种Executor实施及其功能,以便能够找到最符合您要求的方式。