import java.util.concurrent.Semaphore;
public class T11 {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 7; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " 抢到车位" );
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "停车3秒后离开 ");
} catch (Exception e){
e.printStackTrace();
} finally {
semaphore.release();
}
}
},String.valueOf(i)).start();
}
}
}
运行结果: