如何实现自定义同步组件

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();
}
}
}
}
}

转载于:https://www.cnblogs.com/cr1719/p/6912232.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值