synchronized の基本的な使用法と理解


序文

本章内容

` 共有された問題、同期

1. 共有に関する問題

  1. マルチスレッドを実行するプログラムには問題ありません
  2. 問題はマルチスレッドアクセスにあります共享资源
2.1 多个线程读`共享资源`其实也没有问题
2.2 在多个线程对`共享资源`读写操作时发生过指令交错,就会出现问题
  1. コード ブロック内に共享资源マルチスレッドの読み取り操作と書き込み操作のペアがある場合、このコード ブロックは と呼ばれます。临界区

二、synchronized

语法:

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

実際、同期では、クリティカル セクションのコードが外部に対して不可分であり、スレッドの切り替えによって中断されないことが对象锁保証されます。临界区内代码的原子性

2.1 同期オブジェクト指向の記述方法

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 メソッドの同期

成员方法上的写法: ロックされているのは、現在のこのオブジェクトです

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