一、SemaphoreDemo
Semaphore的应用场景就是加锁、异步、控制并发数
下面demo可以理解为抢夺共享资源
import java.util.concurrent.Semaphore; public class SemaphoreDemo { public static void main(String[] args) { String[] name = {"小胖", "大花", "大肥", "小桌子", "小椅子"}; Semaphore semaphore = new Semaphore(3); for (int i = 0; i < 5; i++) { //五个人去争夺三个共享资源 //五个人一放学就去网吧抢机子,网吧只有三台电脑 new Thread(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + "进入网吧"); semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "抢到了电脑"); Thread.sleep(5000); System.out.println(Thread.currentThread().getName() + "下机了"); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } }, name[i]).start(); } } }
运行结果
抢不到电脑的要等别人下机之后才能上网
二、加锁
在调用semaphore.acquire()方法后,进入InterruptedException(),然后点击进入tryAcquireShared()
public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException();