sem.writeLock();
System.out.println("Write op:"+getName());
try {sleep((int)(Math.random()*50));}
catch(InterruptedException 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);
}
}
testSem 类从process类的四个实例开始,它是个线程,用来读或写一个共享文
件。Semaphore类保证访问不会破坏文件,执行程序,输出结果如下:
Trying to get readLock:1
Read op:1
Trying to get readLock:2
Read op:2
Trying to get writeLock:3
Trying to get readLock:4
Read op:4
Unlocking readLock:1
Unlocking readLock:2
Unlocking readLock:4
Write op:3
Unlocking writeLock:3

