package com.company.bingfa;
import java.util.concurrent.Semaphore;
class WC extends Thread{
private Semaphore sem;
WC(Semaphore sem){
this.sem = sem;
}
@Override
public void run() {
if (sem.availablePermits()>0)
System.out.println(getName()+"发现有空位");
else
System.out.println(getName()+"没有位子,等待中..");
try {
sem.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName()+"开始使用...");
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName()+"使用完毕---");
sem.release();
}
}
public class MySemaphore {
public static void main(String[] args) throws InterruptedException {
Semaphore sem = new Semaphore(3);
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
threads[i] = new WC(sem);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
System.out.println("主线程结束");
}
}
来源:CSDN
作者:朴勇佑
链接:https://blog.csdn.net/yongwoozzang/article/details/103604452