public class TestDemo {
public static void main(String[] args) {
//1.创建Semaphore对象
Semaphore semaphore = new Semaphore(3);
//2.循环,开启10个线程
for (int i = 0; i < 10; i++) {
new Thread() {
@Override
public void run() {
try {
// 获得参观权
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + ":开始参观-" + LocalTime.now());
// 参观 2s
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放参观权
semaphore.release();
}
}
}.start();
}
}
}
================================================
public class Test01 {
public static void main(String[] args) {
Semaphore s = new Semaphore(3);
for (int i = 0; i < 10; i++) {
MyThread myThread = new MyThread(s);
myThread.start();
}
}
}
==========================================================
public class MyThread extends Thread {
public Semaphore s;
public MyThread(Semaphore s) {
this.s = s;
}
@Override
public void run() {
try {
s.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName()+":"+"在参观");
s.release();
}
}