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