2、执行类package Thread;
import java.util.concurrent.Semaphore;
/**
* 2017-4-17
* author:饶为
* Administrator
*/
public class SemaphoreThread extends Thread{
private Semaphore semaphore;
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public SemaphoreThread(Semaphore s){
this.semaphore = s;//构造方法 传值semaphore对象 用于释放线程
}
public void run() {
// TODO Auto-generated method stub
java.util.Random
r=new java.util.Random();
int s = r.nextInt(5000)%(1001) +2000; //随机数,用来充当时间的
try {
System.out.println("执行"+s+"秒");
Thread.sleep(s);//假设在执行某个任务,需要s秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
semaphore.release();//释放
System.out.println(semaphore.availablePermits());//查询剩余资源
}
}
}
这里要注意。线程的是否。semaphore.release(),要在线程类中,不能放在执行类中。否则虽然线程类中有Thread.sleep(s),但是执行程序还是会执行下去释放资源,那么马上被别的进程使用了。这个要注意!要我们做完某件事后,才能释放。package Thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* 2017-4-17 author:饶为 Administrator
*/
public class DoSemaphore {
public static void main(String[] args) {
// 线程池
ExecutorService exec = Executors.newCachedThreadPool();
// 只能同时运行5个进程
final Semaphore semaphore = new Semaphore(5);
// SemaphoreThread semaphoreThread= new SemaphoreThread();
// 模拟有100个进程同时运行
for (int i = 0; i < 100; i++) {
SemaphoreThread semaphoreThread = new SemaphoreThread(semaphore);
// 获取可以执行的许可
try {
semaphore.acquire();//在这里获取资源
exec.execute(semaphoreThread);//用线程池去调用我们的线程类。
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 退出线程池
exec.shutdown();
}
}
![java多线程Thread-Semaphore控制信号量 - 饶为 - 饶为先生的博客 java多线程Thread-Semaphore控制信号量 - 饶为 - 饶为先生的博客](http://img1.ph.126.net/fo7DgWz0CyrlDcTiVvyBUQ==/6631872608213388721.png)