很不幸的是在我學習了操做系統以後,發現一下代碼有錯誤。。我會更正 java
由於要用到互斥鎖,可是current包下沒有提供Mutex鎖,因而參見網上的實現用Semaphore實現了一個。不知道會不會有問題,各位拍拍 學習
import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; public class Mutex { private Semaphore s = new Semaphore(1); private AtomicBoolean flag=new AtomicBoolean(true); public void acquire() throws InterruptedException { if(flag.getAndSet(false)){ s.acquire(); } } public void release() { if(!flag.getAndSet(true)){ s.release(); } } public boolean attempt(int ms) { return s.tryAcquire(ms); } public static void main(String[] args) throws InterruptedException { Mutex m = new Mutex(); m.acquire(); m.release(); m.acquire(); m.release(); m.release(); m.acquire(); } }