1 package com.yeepay.sxf.test.atomic.test;
2
3 import java.util.concurrent.Semaphore;
4
5 /**
6 * 測試訊號量
7 * 相當於有一把可以控制併發量的鎖。
8 * 例如銀行櫃檯,只有兩個視窗。但三個人做業務,只允許同時有兩個人能進行做業務
9 *
10 * 多執行緒
11 * @author sxf
12 *
13 */
14 public class TestSemaphore {
15
16 public static void main(String[] args) {
17 //宣告兩個訊號量
18 Semaphore semaphore=new Semaphore(2);
19 //有三個執行緒搶許可證(訊號量)做業務
20 Person person1=new Person("sxf", semaphore);
21 Person person2=new Person("sxs", semaphore);
22 Person person3=new Person("ssy", semaphore);
23 //啟動這三個執行緒工作(同時允許的併發量為2)
24 person1.start();
25 person2.start();
26 person3.start();
27 }
28
29 }
30
31 class Person extends Thread{
32
33 /**
34 * 訊號量(許可證)
35 */
36 private Semaphore semaphore;
37 /**
38 * 當前執行緒的名字
39 */
40 private String cname;
41
42 public Person(String cname,Semaphore semaphore) {
43 this.cname=cname;
44 this.semaphore=semaphore;
45 }
46
47
48 @Override
49 public void run() {
50 System.out.println("Person.run(==>)"+getCname()+" is wating........");
51 try {
52 //獲取許可證
53 semaphore.acquire();
54 System.out.println("Person.run()"+getCname()+" is doneing.......");
55 Thread.sleep(3000);
56 System.out.println("Person.run(==>)"+getCname()+" is service done......");
57 //釋放許可證
58 semaphore.release();
59 } catch (InterruptedException e) {
60 e.printStackTrace();
61 }
62 }
63
64
65 public Semaphore getSemaphore() {
66 return semaphore;
67 }
68
69
70 public void setSemaphore(Semaphore semaphore) {
71 this.semaphore = semaphore;
72 }
73
74
75 public String getCname() {
76 return cname;
77 }
78
79
80 public void setCname(String cname) {
81 this.cname = cname;
82 }
83
84
85
86
87
88
89
90
91
92
93 }