Method execution thread count control method (2)

Source: Internet
Author: User

It is easier to use semaphores to control the number of threads that execute methods at the same time. ViewCode

/*****/Package COM. yq. thread; import Java. util. concurrent. semaphore;/*** @ author yangqiang **/public class service {static Service self = new service (); semaphore = new semaphore (10); public static service getinstance () {return self;} public void Service () {try {semaphore. acquire (); // do something} catch (interruptedexception e) {// not todo} finally {semaphore. release ();}}}

It can be seen that more than 1.5 of Java. util. Concurrent packages need to focus on learning, and it solves many multithreading problems.

The third method is similar to the semaphores. You can use the thread pool execution thread to ensure the number of execution method threads at the same time.

Executorservice executor = executors. newfixedthreadpool (10 );

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.