Java的信号量Semaphore

来源:互联网 发布:犀牛软件基础教程 编辑:程序博客网 时间:2024/04/29 12:55

Semaphore 表示信号量,在Linux的信号量的出现是为了解决共享资源竞争的问题。
其核心概念是:

当请求一个使用信号量来表示的资源时,进程需要先读取信号量的值来判断资源是否可用。大于0,资源可以请求,等于0,无资源可用,进程会进入睡眠状态直至资源可用。当进程不再使用一个信号量控制的共享资源时,信号量的值+1,表示释放资源,其它进程就可以使用。

举例:

public class SemaphoreTest {    public static void main(String[] args) {        // 使用信号量来表示资源。比如现在有3台电脑,有10个学生用。        int N = 10; // 学生数        int C = 3; // 电脑数        Semaphore semaphore = new Semaphore(C);        for(int i = 0; i < N; i++) {             new Student(i, semaphore).start();        }    }}
public class Student extends Thread{    private Semaphore semaphore;    private int i;    public Student(int i, Semaphore semaphore) {        this.semaphore = semaphore;        this.i = i;     }    @Override    public void run() {        try {            semaphore.acquire();            System.out.println("学生" + i + "正在使用电脑..");            try {                Thread.sleep(2000);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("学生" + i + "已经使用完电脑..");            semaphore.release();        } catch (InterruptedException e) {            e.printStackTrace();        }    }}

运行结果:

学生0正在使用电脑..学生1正在使用电脑..学生2正在使用电脑..学生0已经使用完电脑..学生2已经使用完电脑..学生1已经使用完电脑..学生4正在使用电脑..学生3正在使用电脑..学生5正在使用电脑..学生4已经使用完电脑..学生5已经使用完电脑..学生3已经使用完电脑..学生7正在使用电脑..学生6正在使用电脑..学生8正在使用电脑..学生7已经使用完电脑..学生6已经使用完电脑..学生9正在使用电脑..学生8已经使用完电脑..学生9已经使用完电脑..
原创粉丝点击