多线程之信号量

  1. 简单的Semaphore实现
public class Semaphore {
    private boolean signal = false;
    public synchronized void take() {
      this.signal = true;
      this.notify();
     }
public synchronized void release() throws InterruptedException{
    while(!this.signal) wait();
      this.signal = false;
    }
}
  1. 使用Semaphore来发出信号
Semaphore semaphore = new Semaphore();
SendingThread sender = new SendingThread(semaphore);
ReceivingThread receiver = new ReceivingThread(semaphore);
receiver.start();
sender.start();

public class SendingThread {
  Semaphore semaphore = null;
  public SendingThread(Semaphore semaphore){
    this.semaphore = semaphore;
  }
  public void run(){
    while(true){
    //do something, then signal
    this.semaphore.take();
    }
  }
}
public class RecevingThread {
  Semaphore semaphore = null;
   public ReceivingThread(Semaphore semaphore){
    this.semaphore = semaphore;
  }
  public void run(){
    while(true){
      this.semaphore.release();
      //receive signal, then do something...
    }
  }
}
  1. 可计数的Semaphore
public class CountingSemaphore {
  private int signals = 0;
  public synchronized void take() {
    this.signals++;
    this.notify();
  }
  public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
  }
}
  1. 有上限的Semaphore
public class BoundedSemaphore {
  private int signals = 0;
  private int bound   = 0;
  public BoundedSemaphore(int upperBound){
    this.bound = upperBound;
  }
   public synchronized void take() throws InterruptedException{
    while(this.signals == bound) wait();
    this.signals++;
    this.notify();
}
   public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
    this.notify();
  }
}
  1. 把Semaphore当锁来使用
BoundedSemaphore semaphore = new BoundedSemaphore(1);
...
semaphore.take();
  try{
  //critical section
  } finally {
  semaphore.release();
  }

例子:

public class SemaphoreTest {
    public static void main(String[] args) {
        ExecutorService service= Executors.newCachedThreadPool();
        final Semaphore sp=new Semaphore(3);
        for (int i=0;i<10;i++){
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    try {
                        sp.acquire();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    System.out.println("线程"+Thread.currentThread().getName()+"进入,当前已有"+(3-sp.availablePermits()));
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //System.out.println("线程"+Thread.currentThread().getName()+"离开,当前已有"+(3-sp.availablePermits()));
                    sp.release();
                    System.out.println("线程"+Thread.currentThread().getName()+"离开,当前已有"+(3-sp.availablePermits()));

                }
            };
            service.execute(runnable);
        }
    }
}

输出结果:
线程pool-1-thread-1进入,当前已有1
线程pool-1-thread-2进入,当前已有2
线程pool-1-thread-3进入,当前已有3
线程pool-1-thread-2离开,当前已有1
线程pool-1-thread-6进入,当前已有3
线程pool-1-thread-3离开,当前已有2
线程pool-1-thread-1离开,当前已有3
线程pool-1-thread-5进入,当前已有3
线程pool-1-thread-4进入,当前已有2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 多线程并发编程是Java编程中重要的一块内容,也是面试重点覆盖区域,所以学好多线程并发编程对我们来说极其重要...
    嘟爷MD阅读 7,337评论 21 272
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,001评论 19 139
  • 一、多线程 说明下线程的状态 java中的线程一共有 5 种状态。 NEW:这种情况指的是,通过 New 关键字创...
    Java旅行者阅读 4,751评论 0 44
  • 以前出去玩,那是纯玩,现在则多了一份探究与寻觅。世界那么大,不能光照相,还要用眼去看、用心去体会。 今年夏天,两岸...
    林之汐阅读 654评论 0 3
  • 天下杀手,绝门七宗, 这天下江湖有一个组织。名称。七宗,这七宗的第一门。也是宗主,花影凌暮,一个16岁的女孩,因为...
    顾凉诺阅读 193评论 0 0