JAvaは自分でlockロックを実現します
2381 ワード
package com.dinglit.lock;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
/***
*
*
* @author liuhuanchao
* @date 2020-02-01
*/
public class CustomerLockDemo {
public static void main(String[] args) {
MyTask myTask = new MyTask();
for (int i = 1; i < 10; i++) {
new Thread(myTask, "t_" + i).start();
}
}
}
/**
*
*/
class MyTask implements Runnable {
Lock lock = new MyLock();
@Override
public void run() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " ");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
class MyLock implements Lock {
LinkedBlockingQueue queue = new LinkedBlockingQueue();
volatile int status = 0;
@Override
public void lock() {
while (!compareAndSwapInt(0, 1)) {
park();
}
}
private synchronized boolean compareAndSwapInt(int expect, int update) {
if (status == expect) {
status = update;
return true;
}
return false;
}
void park() {
Thread thread = Thread.currentThread();
try {
//
queue.put(thread);
} catch (InterruptedException e) {
e.printStackTrace();
}
// CPU
LockSupport.park();
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public boolean tryLock() {
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public void unlock() {
Thread thread = queue.poll();
if (thread != null) {
status = 0;
LockSupport.unpark(thread);
}
}
@Override
public Condition newCondition() {
return null;
}
}