之前和大家分享过CountDownLatch和CyclicBarrier
======相关链接=====
想了解CountDownLatch的同学请点击埃索达传送门
想了解CyclicBarrier的同学请点击铁炉堡传送门
下面说个场景,例如我有一个资源,只想让2个线程访问,当一个线程释放了资源,其他线程才可以有机会访问这个资源,这样的场景用之前的线程同步工具好像都不太好使,所以这里给大家介绍一个新的工具Semaphore,废话不说直接上代码
public class SemaphoreDemo {
public static void main(String[] args) {
//构造对象,第一个参数为可访问资源的线程数,第二个参数为是否为公平锁,不传默认为公平锁
Semaphore semaphore = new Semaphore(2,false);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" start");
try {
semaphore.acquire();//占用资源
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" end");
semaphore.release();//释放资源
}
};
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(runnable);
thread.start();
try {
thread.sleep(5);//休眠5毫秒,目的让他们有序进入等待队列
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
代码很好理解,首先构造这个类,参数说明看注释,之后锁定资源,释放资源
大家可以拷代码试一试,这个信号量semaphore不难理解,就不多说了