Synchronized difference and Lock, as well as the benefits of using Lock

Synchronized Lock and widely used in concurrent programming in java, under the simple difference between the two terms, recorded

First, both configured

  synchronized keyword, it belongs to JVM level

  Lock is a concrete class, which is part of API-level lock (java.util.concurrent.locks.Lock)

The bottom layer is accomplished by synchronized monitor object

Second, the use

  synchronized without requiring the user to manually release the lock, when synchronized code execution after the system will automatically make the thread releases the lock of occupation

  ReentrantLock the user is required to manually release the lock, if not take the initiative to release the lock, could lead to deadlock. We need to lock () and unlock () method with the try / finally statement block to complete

 

Third, waiting to see if you can break

  synchronized not be interrupted, unless an exception is thrown or normal operation completed

  ReentrantLock interruptible:

    1), set the timeout method tryLock (long timeout, TimeUnit unit)

    2), lockInterruptibly () to put the code block, the call interrupt () method interruptible

Recommended view this blog: https://www.cnblogs.com/dolphin0520/p/3923167.html

 

Fourth, the lock is fair

  synchronized unfair lock

  Both can ReentrantLock, non-default fair locks, construction method can be passed a boolean value, true fair locks, false non-fair locks 

  

 

V. lock bind multiple conditions Condition

  not synchronized

  ReentrantLock used to implement grouping threads need to wake up wake up, wake up accurately, rather than either a synchronized or random wake wake up all the threads.

 Lock的好处,在第五点看来绑定多个Condition  可以精确唤醒,用一下列子来看看:

/**
 * 
 * 编写一个线程,开启三个线程,这三个线程的ID分别为A,B,C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按顺序显示。
 * 如:ABCABCABC... 依次递归
 *
 */
public class TestABCAlternate {
    
    public static void main(String[] args) {
        AlternateDemo ad = new AlternateDemo();
        
        new Thread(new Runnable() {
            public void run() {
                
                for (int i = 1; i <= 20; i++) {
                    ad.loopA(i);
                }
                
            }
        },"A").start();
        
        new Thread(new Runnable() {
            public void run() {
                
                for (int i = 1; i <= 20; i++) {
                    ad.loopB(i);
                }
                
            }
        },"B").start();
        
        new Thread(new Runnable() {
            public void run() {
                
                for (int i = 1; i <= 20; i++) {
                    ad.loopC(i);
                    
                    System.out.println("===========================");
                }
            }
        },"C").start();
    }
}

class AlternateDemo{
    private int number = 1;//当前正在执行线程的标记
    
    private Lock lock = new ReentrantLock();
    
    private Condition condition1 = lock.newCondition();  //多个condition 精确唤醒
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    /**
     * 
     * @param totalLoop : 循环第几轮
     */
    public void loopA(int totalLoop) {
        lock.lock();
        try {
            //1.判断
            while(number!=1) {    //使用while  不使用if  是防止虚假唤醒
                condition1.await();
            }
            //2.打印
            for (int i = 1; i <= 1; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
            }
            //3.唤醒
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            lock.unlock();
        }
    }
    public void loopB(int totalLoop) {
        lock.lock();
        try {
            //1.判断
            while(number!=2) {
                condition2.await();
            }
            //2.打印
            for (int i = 1; i <= 1; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
            }
            //3.唤醒
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            lock.unlock();
        }
    }
    public void loopC(int totalLoop) {
        lock.lock();
        try {
            //1.判断
            while(number!=3) {
                condition3.await();
            }
            //2.打印
            for (int i = 1; i <= 1; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);
            }
            //3.唤醒
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            lock.unlock();
        }
    }
}

 

/** *  * 编写一个线程,开启三个线程,这三个线程的ID分别为A,B,C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按顺序显示。 * 如:ABCABCABC... 依次递归 * */public class TestABCAlternate {public static void main(String[] args) {AlternateDemo ad = new AlternateDemo();new Thread(new Runnable() {public void run() {for (int i = 1; i <= 20; i++) {ad.loopA(i);}}},"A").start();new Thread(new Runnable() {public void run() {for (int i = 1; i <= 20; i++) {ad.loopB(i);}}},"B").start();new Thread(new Runnable() {public void run() {for (int i = 1; i <= 20; i++) {ad.loopC(i);System.out.println("===========================");}}},"C").start();}}
class AlternateDemo{private int number = 1;//当前正在执行线程的标记private Lock lock = new ReentrantLock();private Condition condition1 = lock.newCondition();private Condition condition2 = lock.newCondition();private Condition condition3 = lock.newCondition();/** *  * @param totalLoop : 循环第几轮 */public void loopA(int totalLoop) {lock.lock();try {//1.判断while(number!=1) {condition1.await();}//2.打印for (int i = 1; i <= 1; i++) {System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);}//3.唤醒number = 2;condition2.signal();} catch (Exception e) {// TODO: handle exception} finally {lock.unlock();}}public void loopB(int totalLoop) {lock.lock();try {//1.判断while(number!=2) {condition2.await();}//2.打印for (int i = 1; i <= 1; i++) {System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);}//3.唤醒number = 3;condition3.signal();} catch (Exception e) {// TODO: handle exception} finally {lock.unlock();}}public void loopC(int totalLoop) {lock.lock();try {//1.判断while(number!=3) {condition3.await();}//2.打印for (int i = 1; i <= 1; i++) {System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+totalLoop);}//3.唤醒number = 1;condition1.signal();} catch (Exception e) {// TODO: handle exception} finally {lock.unlock();}}}

Guess you like

Origin www.cnblogs.com/lxwt/p/11345815.html