Semaphore 实现 互斥

来源:互联网 发布:企业数据库管理系统 编辑:程序博客网 时间:2024/05/21 09:15

介绍:Semaphore中管理着一组虚拟的许可,许可的初始数量可通过构造函数来指定【new Semaphore(1);】,执行操作时可以首先获得许可【semaphore.acquire();】,并在使用后释放许可【semaphore.release();】。如果没有许可,那么acquire方法将会一直阻塞直到有许可(或者直到被终端或者操作超时)。

  1. package com.zhy.concurrency.semaphore;  
  2.   
  3. import java.util.concurrent.Semaphore;  
  4.   
  5. /** 
  6.  * 使用信号量机制,实现互斥访问打印机 
  7.  *  
  8.  * @author zhy 
  9.  *  
  10.  */  
  11. public class MutexPrint  
  12. {  
  13.   
  14.     /** 
  15.      * 定义初始值为1的信号量 
  16.      */  
  17.     private final Semaphore semaphore = new Semaphore(1);  
  18.   
  19.     /** 
  20.      * 模拟打印操作 
  21.      * @param str 
  22.      * @throws InterruptedException 
  23.      */  
  24.     public void print(String str) throws InterruptedException  
  25.     {  
  26.         //请求许可  
  27.         semaphore.acquire();  
  28.           
  29.         System.out.println(Thread.currentThread().getName()+" enter ...");  
  30.         Thread.sleep(1000);  
  31.         System.out.println(Thread.currentThread().getName() + "正在打印 ..." + str);  
  32.         System.out.println(Thread.currentThread().getName()+" out ...");  
  33.         //释放许可  
  34.         semaphore.release();  
  35.     }  
  36.   
  37.     public static void main(String[] args)  
  38.     {  
  39.         final MutexPrint print = new MutexPrint();  
  40.   
  41.         /** 
  42.          * 开启10个线程,抢占打印机 
  43.          */  
  44.         for (int i = 0; i < 10; i++)  
  45.         {  
  46.             new Thread()  
  47.             {  
  48.                 public void run()  
  49.                 {  
  50.                     try  
  51.                     {  
  52.                         print.print("helloworld");  
  53.                     } catch (InterruptedException e)  
  54.                     {  
  55.                         e.printStackTrace();  
  56.                     }  
  57.                 };  
  58.             }.start();  
  59.         }  
  60.   
  61.     }  
  62.   
  63. }  
输出结果:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Thread-1 enter ...  
  2. Thread-1正在打印 ...helloworld  
  3. Thread-1 out ...  
  4. Thread-2 enter ...  
  5. Thread-2正在打印 ...helloworld  
  6. Thread-2 out ...  
  7. Thread-0 enter ...  
  8. Thread-0正在打印 ...helloworld  
  9. Thread-0 out ...  
  10. Thread-3 enter ...  
  11. Thread-3正在打印 ...helloworld  
  12. Thread-3 out ...  
通过初始值为1的Semaphore,很好的实现了资源的互斥访问。

0 0
原创粉丝点击