简体   繁体   中英

ExecutorService Java thread limit

I am using ExecutorService for creating Thread . In the run method, its processing a time consuming operations. It takes nearly upto 10 seconds to complete it. For testing, here I am using Thread.sleep(10000);

My question is, If I use newFixedThreadPool as 2000, will it really execute 2000 threads at a time?

public class ThreadPoolTest {

    public static void main(String[] args) {
        System.out.println(new Date());
        ExecutorService executor = Executors.newFixedThreadPool(2000);
        IntStream.range(0, 2000).forEach(
                i -> {
                    Runnable worker = new WorkerThread("WorkerThread-" + i);
                    executor.submit(worker);//calling execute method of ExecutorService
                }
        );
        executor.shutdown();
        while (!executor.isTerminated()) {   }

        System.out.println("Finished all threads");
        System.out.println("Main thread finished");
        System.out.println(new Date());


    }
}


public class WorkerThread implements Runnable{

    private String name;
    public WorkerThread(String s){
        this.name=s;
    }

    public void run() {
        System.out.println(Thread.currentThread().getName()+" (Start) message = "+name);
        processData();

    }

    private void processData(){
        try {  Thread.sleep(10000);  } catch (InterruptedException e) { e.printStackTrace(); }
    }

}

I am printing the time in this code. Its showing that, it took only 10 seconds to complete the entire process. That means all 2000 threads executed parallelly? I have heard that the number of actual threads running will be based on the number of cores in the system. But how did all 2000 threads run parallely?

The number of logical CPUs determines the number of threads running at a given moment.

However, a CPU can switch threads every 100 microseconds or about 10,000 times per second giving the illusion more threads are running at once. Calling sleep is likely to cause the CPU to context switch until after the timeout.

NOTE: System.out.println holds a lock for the output, so in reality, only one thread at a time is doing real work, and even then the program is probably being slowed down by the speed your screen will update. Try removing the println (and the sleep ) and it should complete in a fraction of the time.

But how did all 2000 threads run parallely?

Almost all of them were asleep. The only busy thread was likely to be the one updating the screen with the buffered println messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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