Semaphore 使用案例
程序员文章站
2022-07-12 18:38:01
...
Semaphore即信号量,可以被多个线程获取,下面是一个具体的例子,和Lock配合使用,模拟有三台打印机,一次允许三个线程使用空闲的打印机,代码如下:
package thread; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created with IntelliJ IDEA. * User: malone * Date: 14-4-10 * Time: 上午10:39 * To change this template use File | Settings | File Templates. */ public class SemaphoreDemo { public static void main (String[] args) { Storge storge = new Storge(); for (int i = 0; i < 12; i++) { new MyThread(storge).start(); } } } class Storge { private volatile Boolean[] printer; private Semaphore semaphore; private Lock lock; Storge () { semaphore = new Semaphore(3); printer = new Boolean[3]; for (int i = 0; i < printer.length; i++) { printer[i] = true; } lock = new ReentrantLock(); } public int getFreePrinter () { lock.lock(); try { for (int i = 0; i < printer.length; i++) { if (printer[i]) { printer[i] = false; return i; } } } finally { lock.unlock(); } return -1; } public void setPrinter (int i) { lock.lock(); try { printer[i] = true; } finally { lock.unlock(); } } public void print () { try { //获取信号量 semaphore.acquire(); int freePrinter = getFreePrinter(); System.out.println("Thread " + Thread.currentThread().getName() + " 正在使用" + freePrinter + "号打印机"); Thread.sleep(1000); setPrinter(freePrinter); System.out.println("Thread " + Thread.currentThread().getName() + " 释放" + freePrinter + "号打印机"); } catch (Exception e) { e.printStackTrace(); } finally { semaphore.release(); } } } class MyThread extends Thread { private Storge storge; MyThread (Storge storge) { this.storge = storge; } public void run () { storge.print(); } }
下一篇: Maven下使用jibx插件使用