共享模型之管程(一)

72 阅读13分钟

一、共享带来的问题

两个线程对初始值为 0 的静态变量一个做自增,一个做自减,各做 5000 次,结果是 0 吗?

static int count = 0;
public static void main(String[] args) throws InterruptedException {
    Thread thread1 = new Thread(() -> {
        for(int i = 0; i < 5000; i ++) {
            count ++;
        }
    }, "t1");

    Thread thread2 = new Thread(() -> {
        for(int i = 0; i < 5000; i ++) {
            count --;
        }
    }, "t2");

    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    log.error("count = {}", count);
}

以上的结果可能是正数、负数、零。为什么呢?因为 Java 中对静态变量的自增,自减并不是原子操作,要彻底理解,必须从字节码来进行分析

例如对于 i++ 而言(i 为静态变量),实际会产生如下的 JVM 字节码指令:

getstatic i // 获取静态变量i的值
iconst_1 // 准备常量1
iadd // 自增
putstatic i // 将修改后的值存入静态变量i

并发场景下,当一个线程获取count的要进行自增/减时,由于自增/减并不是原子性操作,在字节码自增/减的过程中又进来线程去操作count影响结果。

eg:count为10,线程操作count++,在加的过程中,又进来一个线程,此时count仍为10,又操作count++,最后count为11。

1.1 临界区 Critical Section

  • 一个程序运行多个线程本身是没有问题的
  • 问题出在多个线程访问共享资源
    • 多个线程读共享资源其实也没有问题
    • 在多个线程对共享资源读写操作时发生指令交错,就会出现问题
  • 一段代码块内如果存在对共享资源的多线程读写操作,称这段代码块为临界区

1.2 竞态条件 Race Condition

多个线程在临界区内执行,由于代码的执行序列不同而导致结果无法预测,称之为发生了竞态条件

二、synchronized 解决方案

为了避免临界区的竞态条件发生,有多种手段可以达到目的。

  • 阻塞式的解决方案:synchronized,Lock
  • 非阻塞式的解决方案:原子变量

本次使用阻塞式的解决方案:synchronized,来解决上述问题,即俗称的【对象锁】,它采用互斥的方式让同一时刻至多只有一个线程能持有【对象锁】,其它线程再想获取这个【对象锁】时就会阻塞住。这样就能保证拥有锁的线程可以安全的执行临界区内的代码,不用担心线程上下文切换。

注意

虽然 java 中互斥和同步都可以采用 synchronized 关键字来完成,但它们还是有区别的:

  • 互斥是保证临界区的竞态条件发生,同一时刻只能有一个线程执行临界区代码
  • 同步是由于线程执行的先后、顺序不同、需要一个线程等待其它线程运行到某个点

2.1 synchronized

语法

synchronized(对象) // 线程1, 线程2(blocked)
{
 	临界区
}

解决

static int count = 0;
static final Object room = new Object();
public static void main(String[] args) throws InterruptedException {
    Thread thread1 = new Thread(() -> {
        for(int i = 0; i < 5000; i ++) {
            synchronized (room) {
                count ++;
            }
        }
    }, "t1");

    Thread thread2 = new Thread(() -> {
        for(int i = 0; i < 5000; i ++) {
            synchronized (room) {
                count --;
            }
        }
    }, "t2");

    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    log.error("count = {}", count);
}

输出:

16:08:44.638 [main] ERROR com.ssm.user.juc.test - count = 0

可以做这样的类比:

  • synchronized(对象) 中的对象,可以想象为一个房间(room),有唯一入口(门)房间只能一次进入一人进行计算,线程 t1,t2 想象成两个人
  • 当线程 t1 执行到 synchronized(room) 时就好比 t1 进入了这个房间,并锁住了门拿走了钥匙,在门内执行count++ 代码
  • 这时候如果 t2 也运行到了 synchronized(room) 时,它发现门被锁住了,只能在门外等待,发生了上下文切换,阻塞住了
  • 这中间即使 t1 的 cpu 时间片不幸用完,被踢出了门外(不要错误理解为锁住了对象就能一直执行下去),这时门还是锁住的,t1 仍拿着钥匙,t2 线程还在阻塞状态进不来,只有下次轮到 t1 自己再次获得时间片时才能开门进入
  • 当 t1 执行完 synchronized{} 块内的代码,这时候才会从 obj 房间出来并解开门上的锁,唤醒 t2 线程把钥匙给他。t2 线程这时才可以进入 obj 房间,锁住了门拿上钥匙,执行它的 count-- 代码.

2.2 思考

synchronized 实际是用对象锁保证了临界区内代码的原子性,临界区内的代码对外是不可分割的,不会被线程切换所打断。

为了加深理解,请思考下面的问题

  • 如果把 synchronized(obj) 放在 for 循环的外面,如何理解?-- 原子性
    • (此时会一次行+-5000)
  • 如果 t1 synchronized(obj1) 而 t2 synchronized(obj2) 会怎样运作?-- 锁对象
    • (两把不同的锁和没加锁结果一样)
  • 如果 t1 synchronized(obj) 而 t2 没有加会怎么样?如何理解?-- 锁对象
    • (只锁一个和不加锁结果一样)

2.3 面向对象改进

把需要保护的共享变量放入一个类

@Slf4j
public class test {
    public static void main(String[] args) throws InterruptedException {
        Room room = new Room();

        Thread thread1 = new Thread(() -> {
            for(int i = 0; i < 5000; i ++) {
                room.increment();
            }
        }, "t1");

        Thread thread2 = new Thread(() -> {
            for(int i = 0; i < 5000; i ++) {
                room.decrement();
            }
        }, "t2");

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
        log.error("count = {}", room.get());
    }
}

class Room {
    int value = 0;
    public void increment() {
        synchronized (this) {
            value++;
        }
    }
    public void decrement() {
        synchronized (this) {
            value--;
        }
    }
    public int get() {
        synchronized (this) {
            return value;
        }
    }
}

三、方法上的 synchronized

3.1 与使用synchronized(X)等效

加在非static方法上等同于锁住当前对象

class Test{
    public synchronized void test() {

    }
}
等价于
class Test{
    public void test() {
        synchronized(this) {

        }
    }
}

加在static方法上等同于锁住类对象

class Test{
    public synchronized static void test() {
        
    }
}
等价于
class Test{
    public static void test() {
        synchronized(Test.class) {

        }
    }
}

锁类对象和锁当前对象,传递对象不一样,为两种锁

3.2 不加 synchronized 的方法

不加 synchronized 的方法 无法保证其原子性

3.3 所谓的“线程八锁”

其实就是考察 synchronized 锁住的是哪个对象

情况1:先1后2 或 先2后1 (同一个对象,采用对象锁,共用一把锁)

@Slf4j(topic = "c.Number")
class Number{
    public synchronized void a() {
        log.debug("1");
    }
    public synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n1.b(); }).start();
}

情况2:1s后1,2 或 2,1s后1 (类一样,采用类对象锁,共用一把锁)

@Slf4j(topic = "c.Number")
class Number{
    public synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n1.b(); }).start();
}

情况3:32,1s后1 或 3,1s后1,2 或 23,1s后1 (ab共用一把锁,但c一定比a快)

@Slf4j(topic = "c.Number")
class Number{
    public synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public synchronized void b() {
        log.debug("2");
    }
    public void c() {
        log.debug("3");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n1.b(); }).start();
    new Thread(()->{ n1.c(); }).start();
}

情况4:2,1s后1 (this当前对象锁,创建了两个对象,两把锁)

@Slf4j(topic = "c.Number")
class Number{
    public synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    Number n2 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n2.b(); }).start();
}

情况5:2,1s后1 (一个类锁,当前对象锁,两种锁)

@Slf4j(topic = "c.Number")
class Number{
    public static synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n1.b(); }).start();
}

情况6:1s后12 或 2,1s后1 (类对象锁,共用一把锁)

@Slf4j(topic = "c.Number")
class Number{
    public static synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public static synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n1.b(); }).start();
}

情况7:2,1s后1 (一个类锁,一个当前对象锁,两把锁)

@Slf4j(topic = "c.Number")
class Number{
    public static synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    Number n2 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n2.b(); }).start();
}

情况8:1s后12 或 2,1s后1 (两个对象,但类一样,共用一把锁)

@Slf4j(topic = "c.Number")
class Number{
    public static synchronized void a() {
        sleep(1);
        log.debug("1");
    }
    public static synchronized void b() {
        log.debug("2");
    }
}

public static void main(String[] args) {
    Number n1 = new Number();
    Number n2 = new Number();
    new Thread(()->{ n1.a(); }).start();
    new Thread(()->{ n2.b(); }).start();
}

四、变量的线程安全分析

4.1 成员变量和静态变量是否线程安全?

  • 如果它们没有共享,则线程安全
  • 如果它们被共享了,根据它们的状态是否能够改变,又分两种情况
    • 如果只有读操作,则线程安全
    • 如果有读写操作,则这段代码是临界区,需要考虑线程安全

4.2 局部变量是否线程安全?

  • 局部变量是线程安全的
  • 但局部变量引用的对象则未必
    • 如果该对象没有逃离方法的作用访问(return),它是线程安全的
    • 如果该对象逃离方法的作用范围,需要考虑线程安全

4.3 局部变量线程安全分析

4.3.1 局部变量例子

public static void test1() {
    int i = 10;
    i++; 
}

并发时,局部变量无线程安全问题,因为局部变量不共享,不管多少个线程来执行,初始值都是10

4.3.2 成员变量例子

class ThreadUnsafe {
    ArrayList<String> list = new ArrayList<>();
    public void method1(int loopNumber) {
        for (int i = 0; i < loopNumber; i++) {
            // { 临界区, 会产生竞态条件
            method2();
            method3();
            // } 临界区
        }
    }
    private void method2() {
        list.add("1");
    }
    private void method3() {
        list.remove(0);
    }
}

存在线程安全问题,list为共享对象,由于list的add和remove都不是原子性操作,所以可能出现删除时list为空的情况

将 list 修改为局部变量

public void method1(int loopNumber) {
    ArrayList<String> list = new ArrayList<>();
    for (int i = 0; i < loopNumber; i++) {
        // { 临界区, 会产生竞态条件
        method2();
        method3();
        // } 临界区
    }
}

此时list为局部变量,不共享,无线程安全问题

4.4 常见线程安全类

  • String
  • Integer
  • StringBuffer
  • Random
  • Vector
  • Hashtable
  • java.util.concurrent 包下的类

这里说它们是线程安全的是指,多个线程调用它们同一个实例的某个方法时,是线程安全的。

  • 它们的每个方法是原子的
  • 注意它们多个方法的组合不是原子的。

4.4.1 线程安全类方法的组合

分析下面代码是否线程安全?

Hashtable table = new Hashtable();
// 线程1,线程2
if( table.get("key") == null) {
    table.put("key", value);
}

单个方法是原子性的,但多个方法一起使用不能保证原子性,并发时有线程安全问题

4.4.2 不可变类线程安全性

String、Integer 等都是不可变类,因为其内部的状态不可以改变,因此它们的方法都是线程安全的

String 有 replace,substring 等方法【可以】改变值啊,那么这些方法又是如何保证线程安全的呢?

例如substring方法,内部String又创建了一个新字符串,把替换后的字符串赋值给新字符串,并未对原字符串进行修改,所以线程安全

4.5 案例分析

例1

public class MyServlet extends HttpServlet {
    // 是否安全?  不安全
    Map<String,Object> map = new HashMap<>();
    // 是否安全?  安全
    String S1 = "...";
    // 是否安全?  安全
    final String S2 = "...";
    // 是否安全?  不安全
    Date D1 = new Date();
    // 是否安全?  不安全(地址不可变,内容可变)
    final Date D2 = new Date();
}

例2

public class MyServlet extends HttpServlet {
    // 是否安全?  不安全(count为成员变量,共享资源)
    private UserService userService = new UserServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}

public class UserServiceImpl implements UserService {
    // 记录调用次数
    private int count = 0;

    public void update() {
        // ...
        count++;
    }
}

例3

public class MyAspect {
    // 是否安全? 不安全(共享成员变量)
    private long start = 0L;

    @Before("execution(* *(..))")
    public void before() {
        start = System.nanoTime();
}

例4

public class MyServlet extends HttpServlet {
    // 是否安全  安全(无改变属性的操作-无状态)
    private UserService userService = new UserServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}

public class UserServiceImpl implements UserService {
    // 是否安全 安全(无改变属性的操作-无状态)
    private UserDao userDao = new UserDaoImpl();

    public void update() {
        userDao.update();
    }
}

public class UserDaoImpl implements UserDao {
    public void update() {
        String sql = "update user set password = ? where username = ?";
        // 是否安全 安全(无成员变量,且Connection对象为方法内的局部变量)
        try (Connection conn = DriverManager.getConnection("","","")){
            // ...
        } catch (Exception e) {
            // ...
        }
    }
}

例5

public class MyServlet extends HttpServlet {
    // 是否安全 安全(无改变属性的操作-无状态)
    private UserService userService = new UserServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}

public class UserServiceImpl implements UserService {
    // 是否安全 安全(无改变属性的操作-无状态)
    private UserDao userDao = new UserDaoImpl();

    public void update() {
        userDao.update();
    }
}

public class UserDaoImpl implements UserDao {
    // 是否安全 不安全(成员变量,共享Connection,且存在close方法)
    private Connection conn = null;
    public void update() throws SQLException {
        String sql = "update user set password = ? where username = ?";
        conn = DriverManager.getConnection("","","");
        // ...
        conn.close();
    }
}

例6

public class MyServlet extends HttpServlet {
    // 是否安全 安全(每次uodate都会创建一个新的UserDaoImpl对象--局部变量)
    private UserService userService = new UserServiceImpl();

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        userService.update(...);
    }
}

public class UserServiceImpl implements UserService {
    public void update() {
        UserDao userDao = new UserDaoImpl();
        userDao.update();
    }
}

public class UserDaoImpl implements UserDao {
    // 是否安全 安全(每次只有一个线程使用,无共享)
    private Connection = null;
    public void update() throws SQLException {
        String sql = "update user set password = ? where username = ?";
        conn = DriverManager.getConnection("","","");
        // ...
        conn.close();
    }
}

例7

public abstract class Test {

    public void bar() {
        // 是否安全 不安全(foo方法内部实现不确定,当foo内部创建线程时,sdf就成了成员方法,被共享)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        foo(sdf);
    }

    public abstract foo(SimpleDateFormat sdf);


    public static void main(String[] args) {
        new Test().bar();
    }
    
}

其中 foo 的行为是不确定的,可能导致不安全的发生,被称之为外星方法

public void foo(SimpleDateFormat sdf) {
    String dateStr = "1999-10-11 00:00:00";
    for (int i = 0; i < 20; i++) {
        new Thread(() -> {
            try {
                sdf.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

五、习题

5.1 卖票练习

public class ExerciseSell {
    public static void main(String[] args) {
        TicketWindow ticketWindow = new TicketWindow(2000);
        List<Thread> list = new ArrayList<>();
        // 用来存储买出去多少张票
        List<Integer> sellCount = new Vector<>();
        for (int i = 0; i < 2000; i++) {
            Thread t = new Thread(() -> {
                // 分析这里的竞态条件
                int count = ticketWindow.sell(randomAmount());
                sellCount.add(count);
            });
            list.add(t);
            t.start();
        }
        list.forEach((t) -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // 卖出去的票求和
        log.debug("selled count:{}",sellCount.stream().mapToInt(c -> c).sum());
        // 剩余票数
        log.debug("remainder count:{}", ticketWindow.getCount());
    }
    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~5
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }
}

class TicketWindow {
    private int count;
    public TicketWindow(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }
    public int sell(int amount) {
        if (this.count >= amount) {
            this.count -= amount;
            return amount;
        } else {
            return 0;
        }
    }
}

count共享,且sell和add方法都有读写操作,线程不安全

解决

public synchronized int sell(int amount) {
    if (this.count >= amount) {
        this.count -= amount;
        return amount;
    } else {
        return 0;
    }
}

sell加锁后线程安全,add内部自带锁,且这两个组合方法的锁为不同对象,不会对共享资源读写操作。

5.2 转账练习

public class ExerciseTransfer {
    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        // 查看转账2000次后的总金额
        log.debug("total:{}",(a.getMoney() + b.getMoney()));
    }
    // Random 为线程安全
    static Random random = new Random();
    // 随机 1~100
    public static int randomAmount() {
        return random.nextInt(100) +1;
    }
}

class Account {
    private int money;
    public Account(int money) {
        this.money = money;
    }
    public int getMoney() {
        return money;
    }
    public void setMoney(int money) {
        this.money = money;
    }
    public void transfer(Account target, int amount) {
        if (this.money > amount) {
            this.setMoney(this.getMoney() - amount);
            target.setMoney(target.getMoney() + amount);
        }
    }
}

解决:

public void transfer(Account target, int amount) {
    synchronized (Account.class) {
        if (this.money > amount) {
            this.setMoney(this.getMoney() - amount);
            target.setMoney(target.getMoney() + amount);
        }
    }
}

要保证两个线程每次只能有一个线程操作,但两个线程分别操作的两个对象,锁当前对象行不通,可锁类对象。