package function.thread;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String args[]){
//这里的信号量大于等待执行线程个数时,线程就会并发执行而不是同步
//因为线程release后,剩余的信号量还是大于0,其余的线程在调用acquire方法时不会被阻塞
Semaphore s = new Semaphore(1);
new IncreThread(s,"A");
new DecThread(s,"B");
}
}
class SharedData{
static int count =10;
}
class IncreThread implements Runnable{
String name;
Semaphore sem;
IncreThread(Semaphore s , String name){
this.name = name;
this.sem = s;
new Thread(this).start();
}
public void run(){
try{
System.out.println(name+" is enter and waitting for permit ........");
sem.acquire();//信号量大于0时会被放行,否则就被阻塞
System.out.println(name+" get a permit ........");
for(int i=0;i<6 ; i++){
Thread.sleep(1000);
SharedData.count++;
System.out.println(name+":"+SharedData.count);
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println(name+" is releaseing a permit ........");
sem.release();
}
}
class DecThread implements Runnable{
String name;
Semaphore sem;
DecThread(Semaphore s , String name){
this.name = name;
this.sem = s;
new Thread(this).start();
}
public void run(){
try{
System.out.println(name+" is enter and waitting for permit ........");
sem.acquire();
System.out.println(name+" get a permit ........");
for(int i=0;i<6 ; i++){
Thread.sleep(1000);
SharedData.count--;
System.out.println(name+":"+SharedData.count);
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println(name+" is releaseing a permit ........");
sem.release();
}
}
运行结果:
A is enter and waitting for permit ........
B is enter and waitting for permit ........
A get a permit ........
A:11
A:12
A:13
A:14
A:15
A:16
A is releaseing a permit ........
B get a permit ........
B:15
B:14
B:13
B:12
B:11
B:10
B is releaseing a permit ........