美文网首页java基础
java锁(2)公平锁

java锁(2)公平锁

作者: 菜鸟上路咯 | 来源:发表于2019-03-22 11:27 被阅读0次

    废话不多说,直接上实例:
    public class Test04 {
    public static void main(String[] args) {
    ExecutorService es = Executors.newCachedThreadPool();
    Some01 some = new Some01();
    for (int i = 0; i < 10; i++) {
    Runnable thread = new MyTread01(some);
    es.execute(thread);
    }
    }

    }

    class MyLock {
    volatile Thread first; // 队首线程
    volatile Boolean isLock = false; // 锁状态字
    volatile BlockingQueue<Thread> waitThread = new ArrayBlockingQueue<Thread>(20); // 等待队列,使用阻塞队列

    // 上锁
    synchronized void lock() throws InterruptedException {
        Thread nowThread = Thread.currentThread();
        while (isLock) { // 锁已被占用,则直接进入等待队列
            waitThread.put(nowThread);
            System.out.println(nowThread.getName() + "进入等待队列");
            wait();
        }
        if (waitThread.isEmpty()) { // 等待队列为空则直接获得锁
            isLock = true;
            System.out.println(nowThread.getName() + "直接获得锁");
        } else {
            while (nowThread != first) { // 不是队首线程则阻塞
                wait();
            }
            isLock = true;
            System.out.println("队首" + nowThread.getName() + "获得锁");
            Thread ft = waitThread.poll(); // 获取到锁后移除队首线程
            System.out.println("等待队列移除" + ft.getName());
        }
    
    }
    
    // 解锁
    synchronized void unLock() {
        isLock = false;
        first = waitThread.peek(); // 获取等待队列队首线程,注意不移除
        notifyAll(); // 没有唤醒指定线程的方法,直接唤醒所有。
    }
    

    }

    //共享资源
    class Some01 {
    private MyLock lock;

    public Some01() {
        this.lock = new MyLock();
    }
    
    public void lock() throws InterruptedException {
        lock.lock();
    }
    
    public void unLock() {
        lock.unLock();
    }
    

    }

    //自定义线程
    class MyTread01 implements Runnable {
    private Some01 some;

    public MyTread01(Some01 some) {
        this.some = some;
    }
    
    public void run() {
        try {
            some.lock();
            System.out.println(Thread.currentThread().getName() + "开始工作");
            Thread.currentThread().sleep(300);
            System.out.println(Thread.currentThread().getName() + "结束工作");
            some.unLock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    

    }

    运行结果为 公平锁结果.PNG
    突然发现Thread是真的不好用,根本没有办法唤醒指定线程,只能转为直接唤醒所有线程,然后判断是否为队首线程,不是则再次堵塞,

    由此可以类推非公平锁的实现,就是将判断是否为队首线程的判断去掉,不再维护等待线程的顺序性,完全由线程间直接竞争,但是效率的确是会比公平锁高。

    相关文章

      网友评论

        本文标题:java锁(2)公平锁

        本文链接:https://www.haomeiwen.com/subject/bfnkvqtx.html