"Multithreading" concurrently executes a specified number of threads

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.