用信号量Semaphore实现互
在Doug lea的那本著名的《Java并发编程—设计原则与模式》,英文名" Concurrent Programming in Java™: Design Principles and Patterns, Second Edition",书中提到可以用信号量Semaphore实现互斥锁Mutex。 虽然java中是通过synchronize关键字提供锁,并用这个基础设施实现信号量的。在有的系统中只有信号量这一原语,锁是通过信号量实现的。代码如下:import java。util。concurrent。 Semaphore;public class Mutex 。。。{
private...全部
在Doug lea的那本著名的《Java并发编程—设计原则与模式》,英文名" Concurrent Programming in Java™: Design Principles and Patterns, Second Edition",书中提到可以用信号量Semaphore实现互斥锁Mutex。
虽然java中是通过synchronize关键字提供锁,并用这个基础设施实现信号量的。在有的系统中只有信号量这一原语,锁是通过信号量实现的。代码如下:import java。util。concurrent。
Semaphore;public class Mutex 。。。{
private Semaphore s = new Semaphore
(1);
public void acquire() throws InterruptedException 。
。。{
s。acquire();
}
public void release()。。。{
s。release();
}
public boolean attempt(int ms) throws InterruptedException 。
。。{
return s。tryAcquire(ms);
}}
上面的代码只能在java5中编译通过,因为Semaphore是在java5中才提供的。我在读上面的代码时有疑问。因为如果错误的连续调用release两次,然后两个线程都调用acquire,岂不是这两个线程都可以同时运行,从而违背了互斥锁的定义?为了证明我的猜测,写了如下的代码:public class TestMutex 。
。。{
public static void main(String[] args) throws InterruptedException。。。{
Mutex mutex=new Mutex();
mutex。
acquire();
mutex。release();
mutex。release();
new MyThread(mutex)。start();
new MyThread(mutex)。start();
}}class MyThread extends Thread。
。。{
private Mutex mutex;
public MyThread(Mutex mutex) 。。。{
this。mutex=mutex;
}
public void run()。
。。{
try 。。。{
mutex。acquire();
} catch (InterruptedException e1) 。。。{
throw new RuntimeException(e1);
}
for(int i=0;i<10;i++)。
。。{
System。out。print(i);
if(i%3==0)。。。{
try 。。。{
Thread。sleep(100);
} catch (InterruptedException e) 。
。。{
e。printStackTrace();
}
}
}
mutex。release();
}} 该程序的输出如下:00123123456456789789从而证实了我的猜测。收起