Synchronized 和 Lock

1、原始构成

Synchronized 是关键字属于JVM层面 (代码中以蓝色字体呈现) monitorenter 、monitorexit Lock 是具体类(java.util.concurrent.locks.lock)是api层面的锁

2、使用方法

Synchronized 不需要用户手动释放锁,当synchronized代码执行完后系统会自动让线程释放对锁的占用 ReentrantLock 需要用户手动释放锁 如果没有释放,就会导致死锁 需要lock() 和 unlock()方法配合try/finally语句块来完成 (Lock需要在while中使用,不能在if里面使用)

3、等待是否可中断

Synchronized 不可中断,除非抛出异常 或 正常运行完成 ReentrantLock 可中断 1>设置超时方法 tryLock(long timeout, TimeUnit unit) 2>lockInterruptibly() 放代码块中,调用 interrup() 方法可中断

4、加锁是否公平

Synchronized 非公平锁 ReentrantLock 两者都可以,默认非公平锁 (可重入锁) 构造方法可以传入 boolean值,true公平锁 false非公平锁

5、锁绑定多个条件Condition

Synchronized 没有 ReentrantLock 用来实现分组唤醒需要唤醒的线程们,可以精确唤醒 而synchronized要么随机唤醒一个,要么全部唤醒

题目:多线程之间顺序调用,实现A->b->C三个线程启动,要求如下:
AA打印5次,BB打印10次,CC打印15次 重复10次

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

/**
 * @Author: LeavesCai7
 * @Date: 2021/01/22 11:29
 * 题目:多线程之间顺序调用,实现A->b->C三个线程启动,要求如下:
 *       AA打印5次,BB打印10次,CC打印15次 重复10次
 *       ReentrantLock
 */

class shareResource{
    private int num = 1; //A:1 B:2 C:3
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print5(){
        lock.lock();
        try{

            //判断
            while (num != 1){
                c1.await();
            }

            //干活
            for (int i =1;i<=5;i++){
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }

            //通知
            num = 2;
            c2.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print10(){
        lock.lock();
        try{

            //判断
            while (num != 2){
                c1.await();
            }

            //干活
            for (int i =1;i<=10;i++){
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }

            //通知
            num = 3;
            c3.signal();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {

            //判断
            while (num != 3) {
                c1.await();
            }

            //干活
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }

            //通知
            num = 1;
            c3.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class SyncAndReentrantLockDemo {
    public static void main(String[] args) {
        shareResource shareResource = new shareResource();

        new Thread(() -> {
            for (int i = 0; i <= 10; i++) {
                shareResource.print5();
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i <= 10; i++) {
                shareResource.print10();
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 0; i <= 10; i++) {
                shareResource.print15();
            }
        },"C").start();

    }
}
posted on 2021-01-22 14:15  LeavesCai7  阅读(203)  评论(0编辑  收藏  举报