如何实现自定义同步组件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何实现自定义同步组件相关的知识,希望对你有一定的参考价值。

package com.chen;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
* desc:自定义同步组件,只允许最多n个线程同时访问
* // 1.共享访问
* // 2.定义n个资源数
* Created by chenjianye on 2017/5/26.
*/
public class ServerLock implements Lock{

private Sync sync = null;

public ServerLock(int ServerLockNum) {
this.sync = new Sync(ServerLockNum);
}

private final class Sync extends AbstractQueuedSynchronizer {

Sync(int count){
setState(count);
}

public int tryAcquireShared(int reduceCount) {
for(;;) {
int current = getState();
int newCount = current - reduceCount;
if (newCount < 0 || compareAndSetState(current, newCount)) {
return newCount;
}
}
}

public boolean tryReleaseShared(int returnCount) {
for(;;) {
int current = getState();
int newCount = current + returnCount;
if (compareAndSetState(current, newCount)) {
return true;
}
}
}

}

@Override
public void lock() {
// sync.acquire(1);
sync.acquireShared(1);
}

@Override
public void unlock() {
sync.releaseShared(1);
}

@Override
public void lockInterruptibly() throws InterruptedException {
System.out.println("dd");
}

@Override
public boolean tryLock() {
return false;
}

@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(1000));
}

@Override
public Condition newCondition() {
throw new RuntimeException("");
}

}


package com.chen;

import java.util.concurrent.locks.Lock;

/**
* desc:测试自定义锁
* Created by chenjianye on 2017/5/26.
*/
public class TestLock {

public static void main(String[] args) {
ServerLock lock = new ServerLock(4);
// ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
// Lock tmp = lock.writeLock();
for(int i=0;i<20;i++) {
Worker worker = new Worker(lock);
worker.start();
}
}

static class Worker extends Thread{

Lock lock;

Worker(Lock lock) {
this.lock = lock;
}

public void run() {
while (true) {
lock.lock();
try{
Thread.sleep(1000);
System.out.println("Thread name:" + Thread.currentThread().getName()+"时间:"+System.currentTimeMillis()/1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
}

以上是关于如何实现自定义同步组件的主要内容,如果未能解决你的问题,请参考以下文章

vue3自定义组件使用v-model实现双向数据绑定

如何在 Angular 中为自定义组件实现伪事件?

深入浅出Java并发编程指南「实战篇」教你如何使用AbstractQueuedSynchronizer实现自己的同步器组件

带有<router-link>的自定义Vue库组件,如何同步路由器状态?

React UI组件库——如何快速实现antd的按需引入和自定义主题

[oldboy-django][2深入django]Form组件实现生成: select下拉框, checkbox复选框,radio单选框以及如何实现自定义数据格式要求