Semaphore(信号量)可以用来控制同时访问特定资源的线程数量
acquire()方法:
当使用acquire()方法时,如果没有或许到许可证就会被堵塞,直至获得了许可证。
tryAcquire()方法:
当使用tryAcquire()方法时,如果没有获取到许可证,就会返回false,不会被堵塞。
acquire()方法
public class SemaphoreExample {public static void main(String[] args) {Semaphore semaphore = new Semaphore(2); // 允许同时访问打印机的线程数量为2for (int i = 1; i <= 5; i++) {new Thread(() -> {try {System.out.println("Thread " + Thread.currentThread().getName() + " is waiting to access the printer");semaphore.acquire(); // 获取许可System.out.println("Thread " + Thread.currentThread().getName() + " is printing");Thread.sleep(2000); // 假设打印需要2秒钟System.out.println("Thread " + Thread.currentThread().getName() + " has finished printing");semaphore.release(); // 释放许可} catch (InterruptedException e) {e.printStackTrace();}}).start(); // 有5个线程想要访问打印机}}
}
输出结果
Thread Thread-0 is waiting to access the printer
Thread Thread-3 is waiting to access the printer
Thread Thread-4 is waiting to access the printer
Thread Thread-1 is waiting to access the printer
Thread Thread-2 is waiting to access the printer
Thread Thread-3 is printing
Thread Thread-0 is printing
Thread Thread-3 has finished printing
Thread Thread-0 has finished printing
Thread Thread-4 is printing
Thread Thread-1 is printing
Thread Thread-4 has finished printing
Thread Thread-1 has finished printing
Thread Thread-2 is printing
Thread Thread-2 has finished printing
tryAcquire()方法
public class SemaphoreExampleTryAcquire {public static void main(String[] args) {Semaphore semaphore = new Semaphore(2); // 允许同时访问打印机的线程数量为2for (int i = 0; i < 5; i++) {new Thread(() -> {if (semaphore.tryAcquire()) {try {System.out.println("Thread " + Thread.currentThread().getName() + " is printing");Thread.sleep(2000); // 假设打印需要2秒钟System.out.println("Thread " + Thread.currentThread().getName() + " has finished printing");semaphore.release(); // 释放许可} catch (InterruptedException e) {e.printStackTrace();}} else {System.out.println("Thread " + Thread.currentThread().getName() + " failed to acquire the semaphore");}}).start(); // 有5个线程想要访问打印机}}
}
输出结果
Thread Thread-0 is printing
Thread Thread-3 failed to acquire the semaphore
Thread Thread-2 failed to acquire the semaphore
Thread Thread-1 is printing
Thread Thread-4 failed to acquire the semaphore
Thread Thread-1 has finished printing
Thread Thread-0 has finished printing