使用semaphore写一个显示锁

时间:2024-10-02 12:07:02
/**
* 这里只是将Semaphore包装了一下,注意当Semaphore的构造参数是1时,本身就是一个显示锁
*/
public class SemaphoreLock { private final Semaphore semaphore = new Semaphore(); public void lock() throws InterruptedException {
semaphore.acquire();
} public void unlock(){
semaphore.release();
} public static void main(String[] args) {
SemaphoreLock lock = new SemaphoreLock(); for(int i=; i<; i++){
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + " is running ");
lock.lock();
System.out.println(Thread.currentThread().getName() + " get the lock ");
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
System.out.println(Thread.currentThread().getName() + " release the lock ");
}).start();
}
} }

这个例子就是把semaphore当成了普通的显示锁

public class SemaphoreLock {
public static void main(String[] args) {
//1、信号量为1时 相当于普通的锁 信号量大于1时 共享锁
Output o = new Output();
for (int i = ; i < ; i++) {
new Thread(() -> o.output()).start();
}
}
}
class Output {
Semaphore semaphore = new Semaphore(); public void output() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " start at " + System.currentTimeMillis());
Thread.sleep();
System.out.println(Thread.currentThread().getName() + " stop at " + System.currentTimeMillis());
}catch(Exception e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}
}

note:这里的semaphore只是当成了"lock",与真实的lock的区别是,真实的lock必须由lock的持有者进行释放,而semaphore可有由其他的线程来释放

相关文章