JUC并发编程可重入锁(十九)

 可重入锁

JUC并发编程可重入锁(十九)_第1张图片

 Synchronized版本

 

package com.xizi.lock;

public class Demo01 {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(()->{
            phone.sms();
        },"A").start();

        new Thread(()->{
            phone.sms();
        },"B").start();
    }
}

class Phone{
    public  synchronized  void sms(){
        System.out.println(Thread.currentThread().getName()+"sms");
        call();
    }
    public  synchronized  void call(){
        System.out.println(Thread.currentThread().getName()+"call");

    }
}

 Lock版本

 

package com.xizi.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo02 {
    public static void main(String[] args) {
        Phone1 phone = new Phone1();

        new Thread(()->{
            phone.sms();
        },"A").start();

        new Thread(()->{
            phone.sms();
        },"B").start();
    }
}

class Phone1{
     Lock lock= new ReentrantLock();
    public  synchronized  void sms(){
        lock.lock();//细节问题 lock.lock(); lock.unlock; //lock 锁必须配对,否则就会死在里面
       try {
           System.out.println(Thread.currentThread().getName()+"sms");
           call();
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           lock.unlock();
       }

    }
    public  synchronized  void call(){

        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"call");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

 

你可能感兴趣的:(JUC并发编程(Java))