publicvoidputItem(Object x){ if (markAsUnused(x)) { available.release(); } }
// Not a particularly efficient data structure; just for demo protected Object[] items = new Object[MAX_AVAILABLE]; protectedboolean[] used = newboolean[MAX_AVAILABLE];
protectedsynchronized Object getNextAvailableItem(){ for (int i = 0; i < MAX_AVAILABLE; ++i) { if (!used[i]) { used[i] = true; return items[i]; } } returnnull; // not reached }
protectedsynchronizedbooleanmarkAsUnused(Object item){ for (int i = 0; i < MAX_AVAILABLE; ++i) { if (item == items[i]) { if (used[i]) { used[i] = false; returntrue; } else { returnfalse; } } } returnfalse; }
publicstaticvoidmain(String[] args){ Pool pool = new Pool(); AtomicInteger coutn = new AtomicInteger(0); for (int i = 0; i < 200; i++) {
publicclassAcquireInterrput{ publicstaticvoidmain(String[] args)throws InterruptedException { Service service = new Service(); Thread a = new Thread(() -> { service.testMethod(); },"A"); a.start(); Thread b = new Thread(() -> { service.testMethod(); },"B"); b.start();
privatestaticclassService{ private Semaphore semaphore = new Semaphore(1);
publicvoidtestMethod(){ // 会报错 try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } // 不会报错 // semaphore.acquireUninterruptibly(); System.out.println(Thread.currentThread().getName() + " begin timer=" + System.currentTimeMillis()); for (int i = 0; i < Integer.MAX_VALUE / 50; i++) { String newString = new String(); Math.random(); } System.out.println(Thread.currentThread().getName() + " end timer=" + System.currentTimeMillis()); semaphore.release(); }
} }
1 2 3 4 5 6 7 8 9 10 11 12
A begin timer=1631353318421 main中断了B B begin timer=1631353318931 java.lang.InterruptedException at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:998) at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1304) at java.util.concurrent.Semaphore.acquire(Semaphore.java:312) at top.bingfabook.one.mysemaphore.AcquireInterrput$Service.testMethod(AcquireInterrput.java:33) at top.bingfabook.one.mysemaphore.AcquireInterrput.lambda$main$1(AcquireInterrput.java:17) at java.lang.Thread.run(Thread.java:745) A end timer=1631353321910 B end timer=1631353322377
publicclassMySemaphore{ publicstaticvoidmain(String[] args){ int N = 8; //工人数 Semaphore semaphore = new Semaphore(5); //机器数目 for (int i = 0; i < N; i++) { new Worker(i, semaphore).start(); } }