Semaphore
package Juc;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* 多个共享资源,多个线程取抢占
* Semaphore
*
*/
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore se =new Semaphore(3);//模拟3个车位
for (int i = 1; i <=6; i++) { //6辆车
new Thread(() -> {
try {
se.acquire();
System.out.println(Thread.currentThread().getName()+"\t 抢到车位!");
int s=(new Random().nextInt(10) + 1);
try{TimeUnit.SECONDS.sleep(s);}catch (Exception e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"\t 停车"+s+"s后离开!");
} catch (Exception e) {
e.printStackTrace();
}finally {
se.release();
}
},String.valueOf(i)).start();
}
}
}