semaphore.java
来自「进程同步问题模拟」· Java 代码 · 共 43 行
JAVA
43 行
public class Semaphore{
//记录希望访问共享资料的线程个数的计数器
private int count;
public Semaphore(int i)
{this.count=i;
}
/**
*信号量p的操作
*信号量本身也是临界资源,所以此方法要加synchronized
*/
public synchronized void P(){
boolean interrupted=false;
//count 为0,当前进程阻塞;
while (count==0){
try{
wait();
}
catch(InterruptedException ie){
ie.printStackTrace();
}
}//while结束
count--;
//如果调 用wait()出现异常,interrupted 为true,终止当前进程
if (interrupted)
Thread.currentThread().interrupt();
}
/**
*信号量V的操作
*信号量本身也是临界资源,所以此方法要加synchronized
*/
public synchronized void V(){
count++;
//激活等待进程,使其进入就绪态;
notify();}
/**设置计数器的函数
*同上,此方法加synchronized*/
public synchronized void setCount(int i)
{count=i;}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?