首页 > 其他 > 详细

Current并发包(四) - lock

时间:2020-08-25 15:44:43      阅读:73      评论:0      收藏:0      [点我收藏+]

LOCK


lock概述

非静态同步方法锁是this

静态同步方法锁的锁对象是当前类的字节码

在JDK1.5中,提供了Lock接口

通过lock方法加锁, 通过该unlock方法解锁

锁的公平和非公平策略

在非公平策略下,线程的执行次数并不均等,甚至会出现较大的差距

在公平策略下,线程的执行次数应该是均等的

从效率角度考虑,非公平的效率会相对较高

synchronized使用的是非公平策略

Lock默认是非公平策略

LockDemo.java
package com.wiscom.lock;
?
public class LockDemo {
?
    static int i = 0;
    public static void main(String[] args) throws InterruptedException {
        // true 为公平策略 false为非公平策略
        Lock l = new ReentrantLock(true);
        
        new Thread(new Add(l)).start();
        new Thread(new Add(l)).start();
?
        Thread.sleep(2000);
        System.out.println(i);
    }
?
}
?
class Add implements Runnable {
    private Lock l;
?
    public Add(Lock l) {
        this.l = l;
    }
?
    @Override
    public void run() {
        // 加锁
        l.lock();
        for (int i = 0; i < 10000; i++) {
            LockDemo.i++;
        }
        // 解锁
        l.unlock();
    }
?
}
?

 

ReadWriteLock -- 读写锁

ReadWriteLock lock = new ReentrantReadWriteLock();

加读锁

lock.readLock();

解读锁

lock.readLock().unlock;

 

其他锁

CountDownLatch

闭锁/线程递减锁

对线程进行计数,在计数归零之前,线程会被阻塞

CountDownLatchDemo.java
package com.wiscom.lock;
?
public class CountDownLatchDemo {
?
    public static void main(String[] args) throws InterruptedException {
?
        CountDownLatch cdl = new CountDownLatch(6);
        new Thread(new Teacher(cdl)).start();
        new Thread(new Student(cdl)).start();
        new Thread(new Student(cdl)).start();
        new Thread(new Student(cdl)).start();
        new Thread(new Student(cdl)).start();
        new Thread(new Student(cdl)).start();
        // 在计数归零之前,需要让主函数所在线程先陷入阻塞
        // 当计数归零之后,自动的放开阻塞
        cdl.await();
        System.out.println("开始考试~~~");
    }
}
class Teacher implements Runnable {
?
    private CountDownLatch cdl;
?
    public Teacher(CountDownLatch cdl) {
        this.cdl = cdl;
    }
?
    @Override
    public void run() {
        try {
            Thread.sleep((long) (Math.random() * 10000));
            System.out.println("考官到达考场~~~");
            // 减少1个计数
            cdl.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
?
}
?
class Student implements Runnable {
?
    private CountDownLatch cdl;
?
    public Student(CountDownLatch cdl) {
        this.cdl = cdl;
    }
?
    @Override
    public void run() {
        try {
            Thread.sleep((long) (Math.random() * 10000));
            System.out.println("考生到达考场~~~");
            cdl.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
?
}

 

Current并发包(四) - lock

原文:https://www.cnblogs.com/minnersun/p/13559800.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!