📄 semaphore.java
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -