多线程并发的学习

package com.example.lib;

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

public class MyLock implements Lock {
private Help help = new Help();

@Override
public void lock() {
help.acquire(1);
}

@Override
public void lockInterruptibly() throws InterruptedException {
help.acquireInterruptibly(1);
}

@Override
public boolean tryLock() {
return help.tryAcquire(1);
}

@Override
public boolean tryLock(long l, TimeUnit timeUnit) throws InterruptedException {
return help.tryAcquireNanos(1,timeUnit.toNanos(l));
}

@Override
public void unlock() {
help.release(1);
}

@Override
public Condition newCondition() {
return help.newCondition() ;
}

private class Help extends AbstractQueuedLongSynchronizer{
@Override
protected boolean tryAcquire(long l) {
//第一个线程进来,可以拿到锁,因此我们可以返回true

//如果第二个线程进来,拿不到锁,返回false
//如果当前进来的线程和当前保存的线程是同一个线程,则可以拿到锁的

//如何判断是第一个线程还是其他线程
long state = getState();
Thread thread = Thread.currentThread();
if(state == 0){
if(compareAndSetState(0, l)){
setExclusiveOwnerThread(thread);
return true;
}
}else if (getExclusiveOwnerThread() == thread){
setState(state+1);
return true;
}
return false;
}

@Override
protected boolean tryRelease(long l) {
//锁的获取和释放一一对应的,调用该线程一定是当前线程
if(Thread.currentThread() != getExclusiveOwnerThread()){
return false;
}

long state = getState() - l;
boolean flag = false;
if(state == 0){
setExclusiveOwnerThread(null);
flag = true;
}
setState(state);
return flag;
}

Condition newCondition(){
return new ConditionObject();
}
}
}






package com.example.lib;

public class MyClass {
private int value = 0;
private MyLock lock = new MyLock();

public void a(){
lock.lock();
System.out.println("a");
b();
lock.unlock();
}

public void b(){
lock.lock();
System.out.println("b");
lock.unlock();
}

public int next(){
lock.lock();
try {
Thread.sleep(300);
return value++;
} catch (InterruptedException e) {
throw new RuntimeException();
}finally {
lock.unlock();
}
}

public static void main(String[] args){
final MyClass myClass = new MyClass();
new Thread(new Runnable() {
@Override
public void run() {
while (true){
myClass.a();
//System.out.println(Thread.currentThread().getId()
//+ "" + myClass.next());
}
}
}).start();

}
}

猜你喜欢

转载自www.cnblogs.com/liunx1109/p/11595186.html