信号量的使用

 
 
 1 package com.ccp.Lc0815;
 2 
 3 import java.util.concurrent.Semaphore;
 4 
 5 public class Test {
 6     public static void main(String[] args) {
 7         //定义一个信号量对象
 8         Semaphore s = new Semaphore(1);
 9         //同时启动5个线程
10 
11         new TestSamaphone("吃货" + 0, s).start();
12         new TestSamaphone("吃货" + 1, s).start();
13         new TestSamaphone("吃货" + 2, s).start();
14         new TestSamaphone("吃货" + 3, s).start();
15         new TestSamaphone("吃货" + 4, s).start();
16 
17 
18 }
19 }
 
  
 
 1 package com.ccp.Lc0815;
 2 
 3 import java.util.concurrent.Semaphore;
 4 //private Semaphore s ;//信号
 5 //s.availablePermits() > 0 返回此信号量中当前可用的许可数。此方法通常用于调试和测试目的。
 6 //s.acquire();//获取到许可证
 7 //s.release();//释放许可证
 8 
 9 public class TestSamaphone extends Thread {
10     //定义一个人的属性
11     private String name ;
12     private Semaphore s ;//信号
13     public TestSamaphone(){
14 
15     }
16     public TestSamaphone(String name , Semaphore s) {
17         this.name = name ;
18         this.s = s;
19     }
20     //重写run方法
21     public void run(){
22         System.out.println(Thread.currentThread().getName() + "我想吃臭豆腐!!");
23         System.out.println(s.availablePermits());
24         if(s.availablePermits() > 0 ){
25             System.out.println(Thread.currentThread().getName() + "太好了,不用排队就可以吃了!!!");
26         }else{
27             System.out.println(Thread.currentThread().getName() + "需要等着了,再忍忍。。。。");
28         }
29         try {
30             Thread.sleep(1000);
31             s.acquire();//获取到许可证
32             System.out.println(s.availablePermits());
33             System.out.println(Thread.currentThread().getName() + "吃了了,真香!!!");
34             System.out.println(Thread.currentThread().getName() + "吃完了,可以让地儿了!!!");
35             s.release();//释放许可证
36             System.out.println(s.availablePermits());
37         } catch (InterruptedException e) {
38             e.printStackTrace();
39         }
40 
41     }
42 }

猜你喜欢

转载自www.cnblogs.com/qsy0021/p/11361642.html