java多线程-Lock

大纲:

  1. Lock接口
  2. synchronized&Lock异同

一、Lock

public interface Lock {
    void lock();
    void lockInterruptibly() throws InterruptedException;
    boolean tryLock();
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    void unlock();
    Condition newCondition();
}
  1. lock()获取锁。
  2. lockInterruptibly()可打断的获取锁方法,仅可打断等待锁的线程。
  3. tryLock()获取锁并返回结果,得到锁的线程返回true,没有拿到锁的线程不再等待并返回false。
  4. tryLock(time)带参数函数,可以传入一个时间,在这个时间内获得锁的线程返回true,没有获得锁返回false,且在这个时间内等在锁的线程可以被打断。
  5. unlock()释放锁。
  6. newCondition 创建一个场景(见下章)。

例:

ReentrantLock为Lock接口唯一实现类
 class Met  {
    Lock lock = new ReentrantLock();

    public void action() {
        String name = Thread.currentThread().getName()+":";
        try {
            lock.lockInterruptibly();
            try {
                for (int i = 0; i < 1000; i++) {
                    System.out.println(name+i);
                }
            }finally {
                System.out.println(name+"unlock");
                lock.unlock();
            }
        } catch (InterruptedException e) {
            System.out.println(name+"interrupted");
        }

    }
}
public class MyRunnable implements Runnable {
    Met met;
    MyRunnable(Met met){
        this.met = met;
    }
    @Override
    public void run() {
         met.action(Thread.currentThread());
    }
}
class TestLock {
    public static void main(String[] args) {
        Met met = new Met();
        MyRunnable myRunnable = new MyRunnable(met);
        Thread thread0 = new Thread(myRunnable);
        Thread thread1 = new Thread(myRunnable);
        thread0.start();
        thread1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

二、synchronized&Lock异同

  1. synchronized代码块内发生异常,锁会自动释放、lock需要在finally中手动释放。
  2. synchronized无法锁的获取情况。
  3. synchronized无法设置超时。
  4. synchronized无法中断等待获取锁的线程。
  5. synchronized无法设置是否公平锁,lock和synchronized默认是非公平锁。
  6. lock和synchronized都是排他、重入锁。
原文地址:https://www.cnblogs.com/liuboyuan/p/10281505.html