Java并发之信号量

来源:互联网 发布:可以美化图片的软件 编辑:程序博客网 时间:2024/04/30 14:13

重入锁死

当一个线程重新获取锁,读写锁或者其他不可重入的同步器时,就可能发生重入锁死。可重入的意思是线程可以重复获得它已经持有的锁

避免重入锁死的方法:
* 编写代码时避免再次获取已经持有的锁
* 使用可重入锁

信号量

Semapore(信号量)是一种线程同步结构,用于在线程间传递信号,以避免出现信号丢失,或者像锁一样用于保护一个关键区域。
下面是一个信号量的简单实现:

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;    }}

take方法发出一个存放在Semaphore内部的信号,而release方法则等待一个信号,当其接收信号后,标记位signal被清空,然后方法终止。

使用Semaphore来产生信号

下面的例子中,两个线程通过Semaphore发出的信号的通知对方

public class SendingThread extends Thread{    Semaphore semaphore = null;    public SendingThread(Semaphore semaphore){        this.semaphore = semaphore;    }    @Override    public void run(){        while (true){            this.semaphore.take();        }    }}public class RecevingThread extends Thread{    Semaphore semaphore = null;    public RecevingThread(Semaphore semaphore){        this.semaphore = semaphore;    }    @Override    public void run(){        try {            while (true){                this.semaphore.release();            }        }catch (InterruptedException e){            e.printStackTrace();        }    }    public static void main(String[] args) {        Semaphore semaphore = new Semaphore();        SendingThread sender = new SendingThread(semaphore);        RecevingThread receiver = new RecevingThread(semaphore);        receiver.start();        sender.start();    }}

其他应用:

可以添加计数功能,添加上限,也可以当锁来使用