Lock和synchronized

Lock

概念:

使用:

lock的源码:

/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;

/**
 * {@code Lock} implementations provide more extensive locking
 * operations than can be obtained using {@code synchronized} methods
 * and statements.  They allow more flexible structuring, may have
 * quite different properties, and may support multiple associated
 * {@link Condition} objects.
 *
 * <p>A lock is a tool for controlling access to a shared resource by
 * multiple threads. Commonly, a lock provides exclusive access to a
 * shared resource: only one thread at a time can acquire the lock and
 * all access to the shared resource requires that the lock be
 * acquired first. However, some locks may allow concurrent access to
 * a shared resource, such as the read lock of a {@link ReadWriteLock}.
 *
 * <p>The use of {@code synchronized} methods or statements provides
 * access to the implicit monitor lock associated with every object, but
 * forces all lock acquisition and release to occur in a block-structured way:
 * when multiple locks are acquired they must be released in the opposite
 * order, and all locks must be released in the same lexical scope in which
 * they were acquired.
 *
 * <p>While the scoping mechanism for {@code synchronized} methods
 * and statements makes it much easier to program with monitor locks,
 * and helps avoid many common programming errors involving locks,
 * there are occasions where you need to work with locks in a more
 * flexible way. For example, some algorithms for traversing
 * concurrently accessed data structures require the use of
 * &quot;hand-over-hand&quot; or &quot;chain locking&quot;: you
 * acquire the lock of node A, then node B, then release A and acquire
 * C, then release B and acquire D and so on.  Implementations of the
 * {@code Lock} interface enable the use of such techniques by
 * allowing a lock to be acquired and released in different scopes,
 * and allowing multiple locks to be acquired and released in any
 * order.
 *
 * <p>With this increased flexibility comes additional
 * responsibility. The absence of block-structured locking removes the
 * automatic release of locks that occurs with {@code synchronized}
 * methods and statements. In most cases, the following idiom
 * should be used:
 *
 *  <pre> {@code
 * Lock l = ...;
 * l.lock();
 * try {
 *   // access the resource protected by this lock
 * } finally {
 *   l.unlock();
 * }}</pre>
 *
 * When locking and unlocking occur in different scopes, care must be
 * taken to ensure that all code that is executed while the lock is
 * held is protected by try-finally or try-catch to ensure that the
 * lock is released when necessary.
 *
 * <p>{@code Lock} implementations provide additional functionality
 * over the use of {@code synchronized} methods and statements by
 * providing a non-blocking attempt to acquire a lock ({@link
 * #tryLock()}), an attempt to acquire the lock that can be
 * interrupted ({@link #lockInterruptibly}, and an attempt to acquire
 * the lock that can timeout ({@link #tryLock(long, TimeUnit)}).
 *
 * <p>A {@code Lock} class can also provide behavior and semantics
 * that is quite different from that of the implicit monitor lock,
 * such as guaranteed ordering, non-reentrant usage, or deadlock
 * detection. If an implementation provides such specialized semantics
 * then the implementation must document those semantics.
 *
 * <p>Note that {@code Lock} instances are just normal objects and can
 * themselves be used as the target in a {@code synchronized} statement.
 * Acquiring the
 * monitor lock of a {@code Lock} instance has no specified relationship
 * with invoking any of the {@link #lock} methods of that instance.
 * It is recommended that to avoid confusion you never use {@code Lock}
 * instances in this way, except within their own implementation.
 *
 * <p>Except where noted, passing a {@code null} value for any
 * parameter will result in a {@link NullPointerException} being
 * thrown.
 *
 * <h3>Memory Synchronization</h3>
 *
 * <p>All {@code Lock} implementations <em>must</em> enforce the same
 * memory synchronization semantics as provided by the built-in monitor
 * lock, as described in
 * <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4">
 * The Java Language Specification (17.4 Memory Model)</a>:
 * <ul>
 * <li>A successful {@code lock} operation has the same memory
 * synchronization effects as a successful <em>Lock</em> action.
 * <li>A successful {@code unlock} operation has the same
 * memory synchronization effects as a successful <em>Unlock</em> action.
 * </ul>
 *
 * Unsuccessful locking and unlocking operations, and reentrant
 * locking/unlocking operations, do not require any memory
 * synchronization effects.
 *
 * <h3>Implementation Considerations</h3>
 *
 * <p>The three forms of lock acquisition (interruptible,
 * non-interruptible, and timed) may differ in their performance
 * characteristics, ordering guarantees, or other implementation
 * qualities.  Further, the ability to interrupt the <em>ongoing</em>
 * acquisition of a lock may not be available in a given {@code Lock}
 * class.  Consequently, an implementation is not required to define
 * exactly the same guarantees or semantics for all three forms of
 * lock acquisition, nor is it required to support interruption of an
 * ongoing lock acquisition.  An implementation is required to clearly
 * document the semantics and guarantees provided by each of the
 * locking methods. It must also obey the interruption semantics as
 * defined in this interface, to the extent that interruption of lock
 * acquisition is supported: which is either totally, or only on
 * method entry.
 *
 * <p>As interruption generally implies cancellation, and checks for
 * interruption are often infrequent, an implementation can favor responding
 * to an interrupt over normal method return. This is true even if it can be
 * shown that the interrupt occurred after another action may have unblocked
 * the thread. An implementation should document this behavior.
 *
 * @see ReentrantLock
 * @see Condition
 * @see ReadWriteLock
 *
 * @since 1.5
 * @author Doug Lea
 */
public interface Lock {

    /**
     * Acquires the lock.
     *
     * <p>If the lock is not available then the current thread becomes
     * disabled for thread scheduling purposes and lies dormant until the
     * lock has been acquired.
     *
     * <p><b>Implementation Considerations</b>
     *
     * <p>A {@code Lock} implementation may be able to detect erroneous use
     * of the lock, such as an invocation that would cause deadlock, and
     * may throw an (unchecked) exception in such circumstances.  The
     * circumstances and the exception type must be documented by that
     * {@code Lock} implementation.
     */
    void lock();

    /**
     * Acquires the lock unless the current thread is
     * {@linkplain Thread#interrupt interrupted}.
     *
     * <p>Acquires the lock if it is available and returns immediately.
     *
     * <p>If the lock is not available then the current thread becomes
     * disabled for thread scheduling purposes and lies dormant until
     * one of two things happens:
     *
     * <ul>
     * <li>The lock is acquired by the current thread; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
     * current thread, and interruption of lock acquisition is supported.
     * </ul>
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while acquiring the
     * lock, and interruption of lock acquisition is supported,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * <p><b>Implementation Considerations</b>
     *
     * <p>The ability to interrupt a lock acquisition in some
     * implementations may not be possible, and if possible may be an
     * expensive operation.  The programmer should be aware that this
     * may be the case. An implementation should document when this is
     * the case.
     *
     * <p>An implementation can favor responding to an interrupt over
     * normal method return.
     *
     * <p>A {@code Lock} implementation may be able to detect
     * erroneous use of the lock, such as an invocation that would
     * cause deadlock, and may throw an (unchecked) exception in such
     * circumstances.  The circumstances and the exception type must
     * be documented by that {@code Lock} implementation.
     *
     * @throws InterruptedException if the current thread is
     *         interrupted while acquiring the lock (and interruption
     *         of lock acquisition is supported)
     */
    void lockInterruptibly() throws InterruptedException;

    /**
     * Acquires the lock only if it is free at the time of invocation.
     *
     * <p>Acquires the lock if it is available and returns immediately
     * with the value {@code true}.
     * If the lock is not available then this method will return
     * immediately with the value {@code false}.
     *
     * <p>A typical usage idiom for this method would be:
     *  <pre> {@code
     * Lock lock = ...;
     * if (lock.tryLock()) {
     *   try {
     *     // manipulate protected state
     *   } finally {
     *     lock.unlock();
     *   }
     * } else {
     *   // perform alternative actions
     * }}</pre>
     *
     * This usage ensures that the lock is unlocked if it was acquired, and
     * doesn't try to unlock if the lock was not acquired.
     *
     * @return {@code true} if the lock was acquired and
     *         {@code false} otherwise
     */
    boolean tryLock();

    /**
     * Acquires the lock if it is free within the given waiting time and the
     * current thread has not been {@linkplain Thread#interrupt interrupted}.
     *
     * <p>If the lock is available this method returns immediately
     * with the value {@code true}.
     * If the lock is not available then
     * the current thread becomes disabled for thread scheduling
     * purposes and lies dormant until one of three things happens:
     * <ul>
     * <li>The lock is acquired by the current thread; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
     * current thread, and interruption of lock acquisition is supported; or
     * <li>The specified waiting time elapses
     * </ul>
     *
     * <p>If the lock is acquired then the value {@code true} is returned.
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
     * the lock, and interruption of lock acquisition is supported,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * <p>If the specified waiting time elapses then the value {@code false}
     * is returned.
     * If the time is
     * less than or equal to zero, the method will not wait at all.
     *
     * <p><b>Implementation Considerations</b>
     *
     * <p>The ability to interrupt a lock acquisition in some implementations
     * may not be possible, and if possible may
     * be an expensive operation.
     * The programmer should be aware that this may be the case. An
     * implementation should document when this is the case.
     *
     * <p>An implementation can favor responding to an interrupt over normal
     * method return, or reporting a timeout.
     *
     * <p>A {@code Lock} implementation may be able to detect
     * erroneous use of the lock, such as an invocation that would cause
     * deadlock, and may throw an (unchecked) exception in such circumstances.
     * The circumstances and the exception type must be documented by that
     * {@code Lock} implementation.
     *
     * @param time the maximum time to wait for the lock
     * @param unit the time unit of the {@code time} argument
     * @return {@code true} if the lock was acquired and {@code false}
     *         if the waiting time elapsed before the lock was acquired
     *
     * @throws InterruptedException if the current thread is interrupted
     *         while acquiring the lock (and interruption of lock
     *         acquisition is supported)
     */
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;

    /**
     * Releases the lock.
     *
     * <p><b>Implementation Considerations</b>
     *
     * <p>A {@code Lock} implementation will usually impose
     * restrictions on which thread can release a lock (typically only the
     * holder of the lock can release it) and may throw
     * an (unchecked) exception if the restriction is violated.
     * Any restrictions and the exception
     * type must be documented by that {@code Lock} implementation.
     */
    void unlock();

    /**
     * Returns a new {@link Condition} instance that is bound to this
     * {@code Lock} instance.
     *
     * <p>Before waiting on the condition the lock must be held by the
     * current thread.
     * A call to {@link Condition#await()} will atomically release the lock
     * before waiting and re-acquire the lock before the wait returns.
     *
     * <p><b>Implementation Considerations</b>
     *
     * <p>The exact operation of the {@link Condition} instance depends on
     * the {@code Lock} implementation and must be documented by that
     * implementation.
     *
     * @return A new {@link Condition} instance for this {@code Lock} instance
     * @throws UnsupportedOperationException if this {@code Lock}
     *         implementation does not support conditions
     */
    Condition newCondition();
}

  • ReentrantLock
  /**
     * ReentrantLock(排他锁)具有完全互斥排他的效果,即同一时刻只允许一个线程访问,这样做虽然虽然保证了实例变量的线程安全性,但效率非常低下。
     */
    Lock lock = new ReentrantLock();

lock(),unlock()

main方法类:

   public static void main(String[] args) {
        LockDemo1 lockDemo1 = new LockDemo1();

        Thread thread = new Thread() {
            @Override
            public void run() {
                this.setName("线程A");

                try {
                     lockDemo1.test1();
                  // lockDemo1.test2();
                    //lockDemo1.test3();
                   //lockDemo1.read();
                    //lockDemo1.write();
                   // lockDemo1.await();
                    //lockDemo1.awaitA();

                } catch (Exception e) {

                    System.out.println("获取失败的线程:" + Thread.currentThread().getName());
                }
            }
        };
        thread.start();


        Thread thread1 = new Thread() {
            @Override
            public void run() {
                this.setName("线程B");
                try {
                    lockDemo1.test1();
                   // lockDemo1.test2();
                  //   lockDemo1.test3();
                  //  lockDemo1.read();
                   // lockDemo1.write();
                  //  lockDemo1.signal();
                   // lockDemo1.awaitB();

                } catch (Exception e) {

                    System.out.println("获取失败的线程:" + Thread.currentThread().getName());
                }
            }
        };
        thread1.start();
    /**
     * lock()
     * 获得锁,如果锁不可用,则当前线程将被禁用以进行线程调度,并处于休眠状态,直到获取锁。
     * 必须主动去释放锁,并且在发生异常时,不会自动释放锁。因此一般来说,使用Lock必须在try{}catch{}块中进行,并且将释放锁的操作放在finally块中进行,以保证锁一定被被释放,防止死锁的发生。
     * 通常使用Lock来进行同步的话,是以下面这种形式去使用的:
     */
    public void test1(){

        try {
            lock.lock();
            System.out.println("获取成功的线程:"+Thread.currentThread().getName());
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //unlock 释放锁
            lock.unlock();
            System.out.println(Thread.currentThread().getName()+"释放了锁");
        }

    }

执行结果为:

获取成功的线程:线程A
线程A释放了锁
获取成功的线程:线程B
线程B释放了锁

tryLock()

   /**
     *tryLock()方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true,如果获取失败(即锁已被其他线程获取),则返回false,也就说这个方法无论如何都会立即返回。在拿不到锁时不会一直在那等待。
     * tryLock(long time, TimeUnit unit)方法和tryLock()方法是类似的,只不过区别在于这个方法在拿不到锁时会等待一定的时间,在时间期限之内如果还拿不到锁,就返回false。
     * 如果如果一开始拿到锁或者在等待期间内拿到了锁,则返回true。
     *   所以,一般情况下通过tryLock来获取锁时是这样使用的:
     */

    public  void test2(){
        if (lock.tryLock()){
            try {
                System.out.println("获取成功的线程:"+Thread.currentThread().getName());
                Thread.sleep(3000);
            //业务逻辑
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName()+"释放了锁");
            }

        }else {
            //没有获取锁,可以操作其他业务
            System.out.println("获取失败的线程:"+Thread.currentThread().getName());
        }


    }

执行结果为:

获取成功的线程:线程A
获取失败的线程:线程B
线程A释放了锁

lockInterruptibly()

 /**
     *lockInterruptibly()方法比较特殊,当通过这个方法去获取锁时,如果线程正在等待获取锁,则这个线程能够响应中断,即中断线程的等待状态。也就使说,当两个线程同时通过lock.lockInterruptibly()想获取某个锁时,假若此时线程A获取到了锁,而线程B只有在等待,那么对线程B调用threadB.interrupt()方法能够中断线程B的等待过程。
     * 由于lockInterruptibly()的声明中抛出了异常,所以lock.lockInterruptibly()必须放在try块中或者在调用lockInterruptibly()的方法外声明抛出InterruptedException。
     * 因此lockInterruptibly()一般的使用形式如下:
     */
    public void test3() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            //业务代码
            System.out.println("获取成功的线程:"+Thread.currentThread().getName());
          Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getName()+"释放了锁");
        }

    }

需要搭配 interrupt()方法中断
执行结果为:

获取成功的线程:线程A
获取失败的线程:线程B
线程A释放了锁

  • ReadWriteLock
    * ReadWriteLock接口就是为了解决这个问题。
     * 读写锁维护了两个锁,一个是读操作相关的锁也成为共享锁,一个是写操作相关的锁 也称为排他锁。通过分离读锁和写锁,其并发性比一般排他锁有了很大提升。
     * Lock readLock()	共享锁,可以多个线程同时读
     * Lock writeLock()	互斥锁,有一个线程在写,其他线程不能写也不能读,只能等待
  • ReentrantReadWriteLock
     * ReentrantReadWriteLock实现了上面讲的ReadWriteLock接口
     * 公平性选择	支持非公平(默认)和公平的锁获取方式,吞吐量上来看还是非公平优于公平
     * 重进入	该锁支持重进入,以读写线程为例:读线程在获取了读锁之后,能够再次获取读锁。而写线程在获取了写锁之后能够再次获取写锁也能够同时获取读锁
     * 锁降级	遵循获取写锁、获取读锁再释放写锁的次序,写锁能够降级称为读锁
     *
   ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

readLock()

    /**
     * 说明thread1和thread2在同时进行读操作。这样就大大提升了读操作的效率。
     * 不过要注意的是,如果有一个线程已经占用了读锁,则此时其他线程如果要申请写锁,则申请写锁的线程会一直等待释放读锁。
     * 如果有一个线程已经占用了写锁,则此时其他线程如果申请写锁或者读锁,则申请的线程会一直等待释放写锁。
     */
    public  void  read(){
        System.out.println(Thread.currentThread().getName()+"正在尝试获取读锁");
        readWriteLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"正在读取数据");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
            System.out.println(Thread.currentThread().getName()+"读取数据完毕,并释放了锁");
        }
    }

执行结果:

线程A正在尝试获取读锁
线程B正在尝试获取读锁
线程B正在读取数据
线程A正在读取数据
线程B读取数据完毕,并释放了锁
线程A读取数据完毕,并释放了锁

writeLock()

  public void write(){
        System.out.println(Thread.currentThread().getName()+"正在尝试获取写锁");
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"正在操作数据");
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
            System.out.println(Thread.currentThread().getName()+"操作数据完毕,并释放了锁");
        }

    }

执行结果为:

线程A正在尝试获取写锁
线程B正在尝试获取写锁
线程A正在操作数据
线程A操作数据完毕,并释放了锁
线程B正在操作数据
线程B操作数据完毕,并释放了锁

  • Condition
    /**
     * condition
     *
     * synchronized关键字与 wait() 和 notify/notifyAll() 方法相结合可以实现 等待/通知机制,ReentrantLock类当然也可以实现,但是需要借助于Condition接口与newCondition() 方法。Condition是JDK1.5之后才有的,
     * 它具有很好的灵活性,比如可以实现多路通知功能也就是在一个Lock对象中可以创建多个Condition实例(即对象监视器),线程对象可以注册在指定的Condition中,从而可以有选择性的进行线程通知,在调度线程上更加灵活。
     * 在使用notify/notifyAll()方法进行通知时,被通知的线程是由JVM选择的,使用ReentrantLock类结合Condition实例可以实现“选择性通知”,这个功能非常重要,而且是Condition接口默认提供的。
     * 而synchronized关键字就相当于整个Lock对象中只有一个Condition实例,所有的线程都注册在它一个身上。如果执行notifyAll()方法的话就会通知所有处于等待状态的线程这样会造成很大的效率问题,
     * 而Condition实例的signalAll()方法 只会唤醒注册在该Condition实例中的所有等待线程# 五、Condition接口
     *
     *
     * void await()	相当于Object类的wait方法
     * boolean await(long time, TimeUnit unit)	相当于Object类的wait(long timeout)方法
     * signal()	相当于Object类的notify方法
     * signalAll()	相当于Object类的notifyAll方法
     *
     */
      Condition condition = lock.newCondition();

使用单个Condition实例实现等待/通知机制:
await()

  public  void await(){
        lock.lock();

        try {
            System.out.println("await的时间"+System.currentTimeMillis());
            condition.await();
            System.out.println("await之后执行"+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

signal()

    public void  signal(){
        lock.lock();
        try {
            System.out.println("signal的时间"+System.currentTimeMillis());
            condition.signal();
            Thread.sleep(3000);
            System.out.println("signal之后执行"+System.currentTimeMillis());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

执行结果:

await的时间1662026825802
signal的时间1662026825802
signal之后执行1662026828803
await之后执行1662026828803

可以看到,await()方法和signal()方法实现了与wait()、notify()同样的功能。
注意: 必须在condition.await()方法调用之前调用lock.lock()代码获得同步监视器,不然会报错。

使用多个Condition实例实现等待/通知机制:

  /**
     * 
     *
     * 从结果上可以看出只有A线程被唤醒了。明显的signalAll()与notifyAll()不一样,它没有唤醒全部wait()的线程。
     */


    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();

    public void awaitA(){

        lock.lock();

        System.out.println("awaitA开始时间"+System.currentTimeMillis());
        try {
            conditionA.await();
            System.out.println("awaitA结束时间"+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void awaitB(){
        lock.lock();

        System.out.println("awaitB开始时间"+System.currentTimeMillis());
        try {
            conditionB.await();
            System.out.println("awaitB结束时间"+System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void signalA(){
        lock.lock();

        try {
            System.out.println("signalA开始时间:"+Thread.currentThread());
            conditionA.signalAll();
            System.out.println("signalA结束时间:"+Thread.currentThread());
        } finally {
            lock.unlock();
        }

    }

    public void signalB(){

        lock.lock();

        try {
            System.out.println("signalB开始时间:"+Thread.currentThread());
            conditionB.signalAll();
            System.out.println("signalB结束时间:"+Thread.currentThread());
        } finally {
            lock.unlock();
        }

    }

这里我又开启了一个线程来执行signal,现在3个线程

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                this.setName("线程C");

                try {
                    //lockDemo1.test1();
                    // lockDemo1.test2();
                    //   lockDemo1.test3();
                    //  lockDemo1.read();
                    // lockDemo1.write();
                    //lockDemo1.signal();
                    lockDemo1.signalA();

                } catch (Exception e) {

                    System.out.println("获取失败的线程:" + Thread.currentThread().getName());
                }
            }
        };
        thread2.start();

执行结果为:

awaitA开始时间1662026948183
signalA开始时间:Thread[线程C,5,main]
signalA结束时间:Thread[线程C,5,main]
awaitB开始时间1662026948183
awaitA结束时间1662026948183

使用Condition实现顺序执行:

 volatile private static int nextPrintWho = 1;
    private static ReentrantLock lock = new ReentrantLock();
    final private static Condition conditionA = lock.newCondition();
    final private static Condition conditionB = lock.newCondition();
    final private static Condition conditionC = lock.newCondition();

    public static void main(String[] args) {

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                this.setName("线程A");
                try {
                    lock.lock();
                    while (nextPrintWho != 1) {
                        conditionA.await();
                    }
                    for (int i = 0; i < 3; i++) {
                        System.out.print("ThreadA" + (i + 1) + "       ");
                    }
                    System.out.println();
                    nextPrintWho = 2;
                    //通知conditionB实例的线程运行
                    conditionB.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        };

        Thread thread2 = new Thread() {

            @Override
            public void run() {
                this.setName("线程B");
                try {
                    lock.lock();
                    while (nextPrintWho != 2) {
                        conditionB.await();
                    }
                    for (int i = 0; i < 3; i++) {
                        System.out.print("ThreadB" + (i + 1) + "       ");
                    }
                    System.out.println();
                    nextPrintWho = 3;
                    //通知conditionC实例的线程运行
                    conditionC.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };

        Thread thread3 = new Thread() {
            @Override
            public void run() {
                this.setName("线程C");
                try {
                    lock.lock();
                    while (nextPrintWho != 3) {
                        conditionC.await();
                    }
                    for (int i = 0; i < 3; i++) {
                        System.out.print("ThreadC" + (i + 1) + "       ");
                    }
                    System.out.println();
                    nextPrintWho = 1;
                    //通知conditionA实例的线程运行
                    conditionA.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        };

        Thread[] aArray = new Thread[5];
        Thread[] bArray = new Thread[5];
        Thread[] cArray = new Thread[5];
        for (int i = 0; i < 5; i++) {
            aArray[i] = new Thread(thread1);
            bArray[i] = new Thread(thread2);
            cArray[i] = new Thread(thread3);
            aArray[i].start();
            bArray[i].start();
            cArray[i].start();

        }


    }

执行结果为:

ThreadA1 ThreadA2 ThreadA3
ThreadB1 ThreadB2 ThreadB3
ThreadC1 ThreadC2 ThreadC3
ThreadA1 ThreadA2 ThreadA3
ThreadB1 ThreadB2 ThreadB3
ThreadC1 ThreadC2 ThreadC3
ThreadA1 ThreadA2 ThreadA3
ThreadB1 ThreadB2 ThreadB3
ThreadC1 ThreadC2 ThreadC3
ThreadA1 ThreadA2 ThreadA3
ThreadB1 ThreadB2 ThreadB3
ThreadC1 ThreadC2 ThreadC3
ThreadA1 ThreadA2 ThreadA3
ThreadB1 ThreadB2 ThreadB3
ThreadC1 ThreadC2 ThreadC3

公平锁 和 非公平锁
Lock锁分为:公平锁 和 非公平锁。
公平锁:表示线程获取锁的顺序是按照线程加锁的顺序来分配的,即先来先得的FIFO先进先出顺序。
非公平锁:是随机获取锁的,和公平锁不一样的就是先来的不一定先的到锁,这样可能造成某些线程一直拿不到锁,结果也就是不公平的了。

 private Lock lock;

    public LockDemo3(boolean bo) {
        this.lock = new ReentrantLock(bo);
    }

    public  void  print(){
        lock.lock();

        try {
            System.out.println("-----"+Thread.currentThread().getName()+"获取了锁");
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        LockDemo3 lockDemo3 = new LockDemo3(false);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"复活了");
                lockDemo3.print();
            }
        };

        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
           threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
            threads[i].start();
        }


    }

非公平结果为:

Thread-1复活了
-----Thread-1获取了锁
Thread-0复活了
-----Thread-0获取了锁
Thread-2复活了
Thread-6复活了
-----Thread-6获取了锁
Thread-7复活了
Thread-8复活了
Thread-4复活了
-----Thread-2获取了锁
Thread-3复活了
-----Thread-3获取了锁
Thread-5复活了
-----Thread-7获取了锁
Thread-9复活了
-----Thread-9获取了锁
-----Thread-8获取了锁
-----Thread-4获取了锁
-----Thread-5获取了锁

公平结果为:

Thread-1复活了
Thread-0复活了
-----Thread-1获取了锁
-----Thread-0获取了锁
Thread-2复活了
-----Thread-2获取了锁
Thread-3复活了
-----Thread-3获取了锁
Thread-4复活了
-----Thread-4获取了锁
Thread-5复活了
-----Thread-5获取了锁
Thread-8复活了
-----Thread-8获取了锁
Thread-9复活了
-----Thread-9获取了锁
Thread-7复活了
-----Thread-7获取了锁
Thread-6复活了
-----Thread-6获取了锁

synchronized

概念:

/**
* Synchronized关键字是C语言实现的
*
* 在字节码ByteCode层面是通过
* monitorenter :进入
* monitorexit: 退出
* monitorexit: 退出
*
* 来实现的,为什么会有2个退出呢?因为一个用于正常退出,一个用于异常退出,像java中的try-catch-finally的finally
*/
在这里插入图片描述

使用:

非静态同步方法:

   public synchronized  void notStaticMethod(){ 
    //锁住的是对象,(同一个对象)其他线程来访问带锁的方法需要阻塞排队,普通方法可以直接调用
     //不是同一个对象时,没有关联,带锁的和普通都可以访问
   }
  • 同步代码块
    锁的是this对象
  synchronized (this){
           //锁住的是对象,(同一个对象)其他线程来访问带锁的方法需要阻塞排队,普通方法可以直接调用
           //不是同一个对象时,没有关联,带锁的和普通都可以访问
       }
锁的Class文件类
   synchronized (SynchronizedClass.class){
            //锁住的是类,只有一个线程,对象(不管是不是同一个对象)能进来,其他线程都被阻塞,连普通方法也不能执行
        }
  • 静态同步方法
 public synchronized static void staticMethod(){
      //锁住的是类,只有一个线程,对象(不管是不是同一个对象)能进来,其他线程都被阻塞,连普通方法也不能执行
   }
  • 可重入
  • public synchronized void method1(){ //可重入锁:当一个线程执行到某个synchronized方法时,比如说method1,而在method1中会调用另外一个synchronized方法method2,此时线程不必重新去申请锁,而是可以直接执行方法method2。 method2(); } public synchronized void method2(){ }

区别

区别如下:

来源:
lock是一个接口,而synchronized是java的一个关键字,synchronized是内置的语言实现;

异常是否释放锁:
synchronized在发生异常时候会自动释放占有的锁,因此不会出现死锁;而lock发生异常时候,不会主动释放占有的锁,必须手动unlock来释放锁,可能引起死锁的发生。(所以最好将同步代码块用try catch包起来,finally中写入unlock,避免死锁的发生。)

是否响应中断
lock等待锁过程中可以用interrupt来中断等待,而synchronized只能等待锁的释放,不能响应中断;

是否知道获取锁
Lock可以通过trylock来知道有没有获取锁,而synchronized不能;

Lock可以提高多个线程进行读操作的效率。(可以通过readwritelock实现读写分离)

在性能上来说,如果竞争资源不激烈,两者的性能是差不多的,而当竞争资源非常激烈时(即有大量线程同时竞争),此时Lock的性能要远远优于synchronized。所以说,在具体使用时要根据适当情况选择。

synchronized使用Object对象本身的wait 、notify、notifyAll调度机制,而Lock可以使用Condition进行线程之间的调度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值