非静态同步方法锁是this
静态同步方法锁的锁对象是当前类的字节码
在JDK1.5中,提供了Lock接口
通过lock方法加锁, 通过该unlock方法解锁
锁的公平和非公平策略
在非公平策略下,线程的执行次数并不均等,甚至会出现较大的差距
从效率角度考虑,非公平的效率会相对较高
synchronized使用的是非公平策略
Lock默认是非公平策略
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 lock = new ReentrantReadWriteLock();
加读锁
lock.readLock();
解读锁
lock.readLock().unlock;
闭锁/线程递减锁
对线程进行计数,在计数归零之前,线程会被阻塞
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(); } } ? }
原文:https://www.cnblogs.com/minnersun/p/13559800.html