Sometimes in order to control concurrency, we need to limit the number of threads that are started each time, using the Executors.newfixedthreadpool (int) method.
Example
A thread class that runs for a few seconds to observe the phenomenon more clearly
Packagecom.nicchagil.study.thread.cnblogs.No01 Start a fixed number of threads;ImportJava.util.concurrent.TimeUnit; Public classMyThreadextendsThread {@Override Public voidrun () {System.out.println ( This. GetName ()); /*set a short stop to see the effect*/ Try{TimeUnit.SECONDS.sleep (3); } Catch(interruptedexception e) {e.printstacktrace (); } }}View Code
Start class
Packagecom.nicchagil.study.thread.cnblogs.No01 Start a fixed number of threads;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classCall { Public Static voidMain (string[] args) {/** Concurrent execution of a specified number of threads*/executorservice es= Executors.newfixedthreadpool (2); for(inti = 0; I < 5; i++) {Es.execute (NewMyThread ()); } es.shutdown (); }}View Code
API Reference
Executors.html.newFixedThreadPool (int)
ExecutorService.html.submit (java.lang.Runnable)
ExecutorService.html.shutdown ()
Java™platform, Standard Edition 7
"Multithreading" concurrently executes a specified number of threads