多线程之 Semaphore

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 ........

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值