ExecutorService和For循环JAVA

时间:2014-02-14 12:02:46

标签: java threadpool

queuedJobs = dataController.getQueuedJobs();

threadExecutor = Executors.newFixedThreadPool(queuedJobs.size());

System.out.println("THE NUMEBR OF JOBS IS "+queuedJobs.size());

for (int i=0; i<queuedJobs.size(); i++){
    System.out.println("THREAD "+i+" CREATED");
    threadExecutor.execute( queuedJobs.get(i) );
}

我创建了一个queuedJobs.size(其中8)的线程池,但for循环每次运行时只执行7或6个作业更改?任何人都可以向我解释这一点,并帮助我每次执行正确的金额吗?

1 个答案:

答案 0 :(得分:0)

我尝试使用10个线程创建一个简单的程序但无法重现此问题,我的代码片段是:

package com.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Executor {

    public static void main(String[] args) {
        List<Thread> queuedJobs = new ArrayList<Thread>();
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));
        queuedJobs.add(new Thread(new MyThreadClass()));

        ExecutorService threadExecutor = Executors.newFixedThreadPool(queuedJobs.size());

        System.out.println("THE NUMEBR OF JOBS IS "+queuedJobs.size());

        for (int i=0; i<queuedJobs.size(); i++){
            System.out.println("THREAD "+i+" CREATED");
            threadExecutor.execute( queuedJobs.get(i) );
        }
    }
}

class MyThreadClass implements Runnable {

    @Override
    public void run() {
        System.out.println("I am running");
    }
}

输出是:

THE NUMEBR OF JOBS IS 10
THREAD 0 CREATED
THREAD 1 CREATED
I am running
THREAD 2 CREATED
I am running
THREAD 3 CREATED
THREAD 4 CREATED
I am running
THREAD 5 CREATED
I am running
THREAD 6 CREATED
I am running
I am running
THREAD 7 CREATED
THREAD 8 CREATED
I am running
I am running
THREAD 9 CREATED
I am running
I am running

请完整发布您的代码段以进一步调查。