使用信号量的方式来控制同时执行方法的线程数,这个就比较简单了。看代码
/**
*
*/
package com.yq.thread;
import java.util.concurrent.Semaphore;
/**
* @author yangqiang
*
*/
public class Service {
static Service self = new Service();
Semaphore 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();
}
}
}
可见1.5以上的 java.util.concurrent包要重点学习,它解决了很多多线程的难题。
第三种方式和信号量的类似,可以使用线程池执行线程,保证同一时刻执行方法线程数的数量。
ExecutorService executor = Executors.newFixedThreadPool(10);