简体   繁体   English

ExecutorService和For循环JAVA

[英]ExecutorService and For loop JAVA

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) );
}

I create a pool of threads of queuedJobs.size (which 8) but the for loop only executes 7 or 6 jobs changing each time I run it? 我创建了一个queuedJobs.size(8个)线程池,但是for循环每次执行时仅执行7或6个更改的作业? Can anyone explain this to me and help me execute the right amount each time? 谁能向我解释一下,并帮助我每次执行正确的金额?

I tried creating a simple program with 10 threads but unable to reproduce this issue, my code snippet is: 我尝试创建一个具有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");
    }
}

Output is: 输出为:

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

Please post full your code snippet to investigate further. 请张贴完整的代码段以进行进一步调查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM