import ncurrent
public class Mutex
private Semaphore s = new Semaphore(
public void acquire() throws InterruptedException
s
}
public void release()
s
}
public boolean attempt(int ms) throws InterruptedException
return s
}
}
上面的代碼只能在java
public class TestMutex
public static void main(String[] args) throws InterruptedException
Mutex mutex=new Mutex();
mutex
mutex
mutex
new MyThread(mutex)
new MyThread(mutex)
}
}
class MyThread extends Thread
private Mutex mutex;
public MyThread(Mutex mutex)
this
}
public void run()
try
mutex
} catch (InterruptedException e
throw new RuntimeException(e
}
for(int i=
System
if(i%
try
Thread
} catch (InterruptedException e)
e
}
}
}
mutex
}
}
該程序的輸出如下
從而證實了我的猜測
作為對比
public class TestLock
public static void main(String[] args) throws InterruptedException
new MyThread
new MyThread
}
}
class MyThread
public void run()
synchronized(TestLock
for(int i=
System
if(i%
try
Thread
} catch (InterruptedException e)
e
}
}
}
}
}
}
該程序的輸出如下
可見兩個線程確實互斥運行
這個問題產生的原因是雖然在Mutex的定義中
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26275.html