### 1、Java并发编程相关类库
Java中,并发相关的类库包含三个:
- java.util.concurrent :实用类通常在并发编程中有用。该软件包包括一些小的标准化可扩展框架,以及一些提供有用功能的类,以及其他繁琐或难以实现的。
- java.util.concurrent.atomic: 一个小型工具包,支持对单个变量进行无锁线程安全编程。
- java.util.concurrent.locks: 接口和类,提供用于锁定和等待与内置同步和监视器不同的条件的框架。该框架在锁和条件的使用方面允许更大的灵活性,代价是更笨拙的语法。
Lock接口支持语义不同的锁定规则(可重入,公平等),并且可用于非块结构的上下文,包括手动和锁定重新排序算法。主要实现是ReentrantLock。
这三个类库简称**JUC**。
### 2、Synchronized关键字和Lock接口
#### 2.1、synchronized 关键字
synchronized 是并发编程中重要的使用工具之一,它是JVM自带的关键字,可在需要线程安全的业务场景中使用,来保证线程安全。
- synchronized 关键字可以用来修饰方法和代码块。
```java
//synchronized 修饰方法
public synchronized void method(){
System.out.println("This is a method modified by synchronized!");
}
//synchronized 修饰代码块
public void method2() {
synchronized(this) {
System.out.println("This is a code block modified by synchronized!");
}
}
```
- synchronized按照锁的对象区分可以分为对象锁和类锁
- 对象锁: 当synchronized修饰普通方法或普通代码块时,对类的实例对象、类的调用者加锁。不同的实例对象(类的调用者)获得不同的对象锁。
- 类锁:当synchronized修饰静态方法或修饰Class.class时,对整个类加锁,不同的实例对象(类的调用者)获得同一个的类锁。
以下面代码为例,其中thread1和thread2获得不同的对象锁,thread5和thread6获得同一把类锁,thread2和thread4获得同一把对象锁。
```java
package concourrency;
/**
* @ClassName: Test
* @Description TODO
* @User: miantiao
* @Date 2020/4/15 12:28
* @Version: 1.0
**/
public class Test {
public static void main(String[] args) {
Test test1 = new Test();
Test test2 = new Test();
Test test3 = new Test();
Test test4 = new Test();
new Thread(() -> { test1.method1(); }, "thread1").start();
new Thread(() -> { test2.method1(); }, "thread2").start();
new Thread(() -> { test1.method1(); }, "thread3").start();
new Thread(() -> { test2.method2(); }, "thread4").start();
new Thread(() -> { test3.method4(); }, "thread5").start();
new Thread(() -> { test4.method5(); }, "thread6").start();
}
//对象锁
public synchronized void method1() {
System.out.println("This is method1-----"+Thread.currentThread().getName());
}
//对象锁
public void method2() {
synchronized (this) {
System.out.println("This is method2-----"+Thread.currentThread().getName());
}
}
//不加锁
public void method3() {
System.out.println("This is method3-----"+Thread.currentThread().getName());
}
//类锁
public static synchronized void method4() {
System.out.println("This is method4-----"+Thread.currentThread().getName());
}
//类锁
public synchronized void method5() {
synchronized (Test.class){
System.out.println("This is method5-----"+Thread.currentThread().getName());
}
}
}
```
#### 2.2、Lock接口

Java并发编程学习笔记(三)