我正在用Java实现Mutex,代码如下所示,我不知道为什么结果与我的预期不符, 正如您在我显示的结果中看到的,它的运行是不可预测的
enum MutexStatus {
FREE, BUSY
};
enum FunctionTypes {
INCREASE, DECREASE
};
class Mutex {
private MutexStatus mutexStatus;
public Mutex() {
mutexStatus = MutexStatus.FREE;
}
public void acquire() {
synchronized (this) {
while (mutexStatus == MutexStatus.BUSY)
;
mutexStatus = MutexStatus.BUSY;
}
}
public void release() {
mutexStatus = MutexStatus.FREE;
}
}
class MyThread extends Thread {
private static Mutex mutex = new Mutex();
private static Integer sharedCounter = 0;
private FunctionTypes funcType;
public MyThread(String name, FunctionTypes functionType) {
super.setName(name);
funcType = functionType;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
mutex.acquire();
switch (funcType) {
case INCREASE:
sharedCounter++;
System.out.println(Thread.currentThread().getName() + " -> "
+ sharedCounter);
break;
case DECREASE:
sharedCounter--;
System.out.println(Thread.currentThread().getName() + " -> "
+ sharedCounter);
break;
default:
break;
}
mutex.release();
}
}
}
public class MutexImplement {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread IncreaseThread = new MyThread("Increase thread",
FunctionTypes.INCREASE);
IncreaseThread.start();
MyThread DecreaseThread = new MyThread("Decrease thread",
FunctionTypes.DECREASE);
DecreaseThread.start();
}
}
<小时/>
结果是
>Increase thread -> 1
>Decrease thread -> 0
>Increase thread -> 1
>Decrease thread -> 0
>Decrease thread -> 1
>Increase thread -> 1
>...........
最佳答案
看看 http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html 中的 17.4 。线程将拥有它们自己共享(或实际上不共享)的变量的本地副本。正如已经建议的那样,使共享变量不稳定或使用一些同步/并发控制。您可能还想看看自旋循环(while 循环)并使用一些信号。
现在 Java 有很多构造可以为您完成这一切,尽管我怀疑您已被要求自己创建互斥体。为了记录,请尝试避免使用自己的自制软件并尝试使用提供的并发结构。
关于Java 互斥体实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22859248/