Ken*_*ton 2 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);
// }
}
}
}
Run Code Online (Sandbox Code Playgroud)
这些问题通常通过线程池来解决,您可以向其中提供任务并等待完成.在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();
Run Code Online (Sandbox Code Playgroud)
池将并行处理您的任务.如果您需要控制任务的执行,等待它们的完成,取消它们,获取它们的工作结果等,只需使用Future该submit()方法返回的对象.只要您需要,您可以使用游泳池,但不要忘记在不再需要它时将其关闭.
了解有关各种Executor实现及其功能的更多信息,以便能够以最佳方式找到最符合您要求的实现.
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |