📄 testsem.java
字号:
class Semaphore {
final static int EMPTY = 0;
final static int READING = 1;
final static int WRITING = 2;
protected int state = EMPTY;
protected int readCnt = 0;
public synchronized void readLock() {
if(state == EMPTY) {
state = READING;
}
else if(state == READING) {}
else if(state == WRITING) {
while(state == WRITING) {
try{
wait();
}catch(Exception e){}
}
state = READING;
}
readCnt++;
return;
}
public synchronized void writeLock() {
if(state == EMPTY) {
state = WRITING;
}
else {
while(state != EMPTY) {
try{
wait();
}catch(Exception e){}
}
}
}
public synchronized void readUnlock() {
readCnt--;
if(readCnt == 0) {
state = EMPTY;
notify();
}
}
public synchronized void writeUnlock() {
state = EMPTY;
notify();
}
}
class process extends Thread {
String op;
Semaphore sem;
process(String name,String op,Semaphore sem) {
super(name);
this.op = op;
this.sem = sem;
start();
}
public void run() {
if(op.compareTo("read") == 0) {
System.out.println("Try to get readLock"+getName());
sem.readLock();
System.out.println("Read op:"+getName());
try{
sleep((int)Math.random()*50);
}catch(Exception e){}
System.out.println("Unlocking readLock:"+getName());
sem.readUnlock();
}
else if(op.compareTo("write") == 0) {
System.out.println("Try to get writeLock"+getName());
sem.writeLock();
System.out.println("Write op:"+getName());
try{
sleep((int)Math.random()*50);
}catch(Exception e){}
System.out.println("Unlocking writeLock:"+getName());
sem.writeUnlock();
}
}
}
public class testSem {
public static void main(String argv[]) {
Semaphore lock = new Semaphore();
new process("1","read",lock);
new process("2","read",lock);
new process("3","write",lock);
new process("4","read",lock);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -