介绍:Semaphore中管理着一组虚拟的许可,许可的初始数量可通过构造函数来指定【new Semaphore(1);】,执行操作时可以首先获得许可【semaphore.acquire();】,并在使用后释放许可【semaphore.release();】。如果没有许可,那么acquire方法将会一直阻塞直到有许可(或者直到被终端或者操作超时)。
- package com.zhy.concurrency.semaphore;
- import java.util.concurrent.Semaphore;
- /**
- * 使用信号量机制,实现互斥访问打印机
- *
- * @author zhy
- *
- */
- public class MutexPrint
- {
- /**
- * 定义初始值为1的信号量
- */
- private final Semaphore semaphore = new Semaphore(1);
- /**
- * 模拟打印操作
- * @param str
- * @throws InterruptedException
- */
- public void print(String str) throws InterruptedException
- {
- //请求许可
- semaphore.acquire();
- System.out.println(Thread.currentThread().getName()+" enter ...");
- Thread.sleep(1000);
- System.out.println(Thread.currentThread().getName() + "正在打印 ..." + str);
- System.out.println(Thread.currentThread().getName()+" out ...");
- //释放许可
- semaphore.release();
- }
- public static void main(String[] args)
- {
- final MutexPrint print = new MutexPrint();
- /**
- * 开启10个线程,抢占打印机
- */
- for (int i = 0; i < 10; i++)
- {
- new Thread()
- {
- public void run()
- {
- try
- {
- print.print("helloworld");
- } catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- }
- }
- Thread-1 enter ...
- Thread-1正在打印 ...helloworld
- Thread-1 out ...
- Thread-2 enter ...
- Thread-2正在打印 ...helloworld
- Thread-2 out ...
- Thread-0 enter ...
- Thread-0正在打印 ...helloworld
- Thread-0 out ...
- Thread-3 enter ...
- Thread-3正在打印 ...helloworld
- Thread-3 out ...