forked from zhaoshiling1017/ThreadProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySemaphore.java
More file actions
42 lines (41 loc) · 1.17 KB
/
Copy pathMySemaphore.java
File metadata and controls
42 lines (41 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.unicss;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class MySemaphore extends Thread {
Semaphore position;
private int id;
public MySemaphore(int i,Semaphore s){
this.id=i;
this.position=s;
}
public void run(){
try{
if(position.availablePermits()>0){
System.out.println("顾客["+this.id+"]进入厕所,有空位");
}
else{
System.out.println("顾客["+this.id+"]进入厕所,没空位,排队");
}
position.acquire();
System.out.println("顾客["+this.id+"]获得坑位");
Thread.sleep((int)(Math.random()*1000));
System.out.println("顾客["+this.id+"]使用完毕");
position.release();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]){
ExecutorService list=Executors.newCachedThreadPool();
Semaphore position=new Semaphore(2);
for(int i=0;i<10;i++){
list.submit(new MySemaphore(i+1,position));
}
list.shutdown();
position.acquireUninterruptibly(2);
System.out.println("使用完毕,需要清扫了");
position.release(2);
}
}