java自己实现一个lock锁

 

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

 

你可能感兴趣的:(java)