Multithreading learning

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 newCondition for condition Condition () { return help.newCondition (); } Private class Help the extends AbstractQueuedLongSynchronizer { @Override protected Boolean to tryAcquire ( Long L) { // first thread come, can get the lock, so we can return to true // If the second thread comes in, can not get a lock, return false // if the current thread and come in to save the current thread is a thread with, you can get a lock






















// how to determine a first thread or other thread Long getState State = (); . = The Thread the Thread Thread currentThread (); IF (State == 0) { IF (compareAndSetState ( 0, L)) { setExclusiveOwnerThread (Thread) ; return to true; } } the else IF (getExclusiveOwnerThread () == Thread) { the setState (State + . 1); return to true; } return to false; } @Override protected Boolean tryRelease ( Long L) { // lock acquisition and release of eleven corresponding to the calling thread must be the current thread IF (the thread. currentThread () = getExclusiveOwnerThread ()!) { return to false; } Long State = getState () - L; Boolean in 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();

}
}

Guess you like

Origin www.cnblogs.com/liunx1109/p/11595186.html