synchronized基本使用和理解


前言

本章内容

`共享问题、synchronized

一、共享存在的问题

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

二、synchronized

语法:

		synchronized(对象){
    
    
            //临界区
        }

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

2.1 synchronized面向对象写法

public class App {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Room room = new Room();
        Thread t1 = new Thread(() -> {
    
    
            for (int i = 1; i <= 5000; i++) {
    
    
                room.inc();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
    
    
            for (int i = 1; i <= 5000; i++) {
    
    
                room.dec();
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();//等待t1线程执行完毕
        t2.join();//等待t2线程执行完毕
        System.out.println(room.getCount());
    }
}

class Room {
    
    
    private int count = 0;

    public void inc() {
    
    
        synchronized (this) {
    
    
            count++;
        }
    }
    public void dec() {
    
    
        synchronized (this) {
    
    
            count--;
        }
    }
    public int getCount() {
    
    
        synchronized (this) {
    
    
            return count;
        }
    }
}

2.2 方法上的synchronized

成员方法上的写法:锁住的是当前的this对象

class Room{
    public synchronized void inc(){
        //代码
    }
}

等价于

class Room {
    public void inc() {
        synchronized (this) {
            //代码
        }
    }
}

静态方法上的写法:锁住的是类对象 XXX.class

class Room {
    public static synchronized void inc() {
        //代码
    }
}

等价于

class Room {
    public static void inc(){
        synchronized (Room.class){
            //代码
        }
    }
}

总结

提示:这里对文章进行总结:

猜你喜欢

转载自blog.csdn.net/m0_50677223/article/details/130660112