• synchronized


    synchronized原理

           引入锁机制以解决线程安全问题:
    悲观锁:当存在多个线程操作共享数据时,需要保证同一时刻有且只有一个线程在操作共享数据,其他线程必须等到该线程处理完数据后再进行
    乐观锁:CAS  compare and set

           在添加synchronized关键字后就可以保证在一个时刻上只有一个线程在调用某个方法或者代码块,不会出现并发的情形,达到排队执行的效果。 

           在Java中synchronized可保证在同一个时刻,只有一个线程可以执行某个方法或者某个代码块(主要是对方法或者代码块中存在共享数据的操作),同时还应该注意到synchronized另外一个重要的作用,synchronized可保证一个线程的变化(主要是共享数据的变化)被其他线程所看到(保证可见性,完全可以替代volatile功能),这点确实也是很重要的。 

           对象在内存中存储时可以分为对象头、实例数据和对齐字节三部分。对象头数据一般包含标识字mark word和类型指针klass pointer;实例数据就是具体对象的成员数据,一般按照4B为的单位进行数据存储;最后的对齐字节用于将对象存储的数据凑够8字节的整数倍。

    • Mark Word:默认存储对象的HashCode,分代年龄和锁标志位信息。这些信息都是与对象自身定义无关的数据,所以Mark Word被设计成一个非固定的数据结构以便在极小的空间内存存储尽量多的数据。它会根据对象的状态复用自己的存储空间,也就是说在运行期间Mark Word里存储的数据会随着锁标志位的变化而变化
    • Klass Pointer:对象指向它的类元数据的指针,虚拟机通过这个指针来确定这个对象是哪个类的实例。
    • synchronized用的锁是存在Java对象头里的,存在锁对象的对象头的Mark Word中

          synchronized用于实现同步处理,保证共享数据的安全性
          数据有安全性问题的原因:1、共享数据 2、修改数据
          synchronized相对于volatile是重量级的线程安全的方法,可以保证3大特性:原子性、可见性、有序性。
          可以将并发操作转换为串型执行 

    锁的三种使用方法

    - synchronized同步方法   在方法上添加同步关键字,当前的锁对象为当前对象---对象锁

    1. public class A2 {
    2. public static void main(String[] args) throws Exception {
    3. NumOper no = new NumOper(100);
    4. Thread[] ts = new Thread[4];
    5. for (int i = 0; i < 2; i++) {
    6. ts[i * 2] = new Thread(() -> {
    7. for (int k = 0; k < 50; k++)
    8. no.add();
    9. });
    10. ts[i * 2].start();
    11. ts[i * 2 + 1] = new Thread(() -> {
    12. for (int k = 0; k < 50; k++)
    13. no.sub();
    14. });
    15. ts[i * 2 + 1].start();
    16. }
    17. for (Thread tmp : ts)
    18. tmp.join();
    19. System.out.println("Main:" + no.getNum());
    20. }
    21. }
    22. /*
    23. * 以new出来的NumOper对象充当锁,当前对象内的所有synchronized方法在不同线程调用时互斥,
    24. * 但是可以直接访问非synchronized方法。注意synchronized允许持有锁的线程重入
    25. */
    26. class NumOper {
    27. private int num;
    28. public NumOper(int num) { //synchronized不能添加在构造器上
    29. this.num = num;
    30. }
    31. public synchronized void add() {
    32. System.out.println(Thread.currentThread() + "....add...begin:" + this.num);
    33. this.num++;
    34. sub();
    35. System.out.println(Thread.currentThread() + "....add...end" + this.num);
    36. }
    37. public synchronized void sub() {
    38. System.out.println(Thread.currentThread() + "....sub...begin" + this.num);
    39. this.num--;
    40. System.out.println(Thread.currentThread() + "....sub...end" + this.num);
    41. }
    42. public int getNum() {
    43. return this.num;
    44. }
    45. }

    - synchronized同步静态方法  以当前类Class对象作为锁---类锁
            针对一个类一般只会存储一个

    1. public class A3 {
    2. public static void main(String[] args) {
    3. for (int i = 0; i < 5; i++) {
    4. new Thread(() -> {
    5. for (int k = 0; k < 10; k++)
    6. new S3();
    7. }).start();
    8. }
    9. try {
    10. Thread.sleep(1000);
    11. } catch (InterruptedException e) {
    12. e.printStackTrace();
    13. }
    14. System.out.println(S3.getCounter());
    15. }
    16. }
    17. class S3 {
    18. private static int counter = 0;
    19. public S3() {
    20. add();
    21. }
    22. private synchronized static void add() {
    23. System.out.println(Thread.currentThread() + "开始创建操作" + counter);
    24. counter++;
    25. eee();
    26. System.out.println(Thread.currentThread() + "完成创建操作" + counter);
    27. }
    28. public synchronized static void eee() {
    29. }
    30. public static int getCounter() {
    31. return counter;
    32. }
    33. }

    - synchronized同步代码块   自定义对象充当锁

    1. public class A {
    2. public static void main(String[] args) {
    3. for(int i=0;i<3;i++) {
    4. Thread t1=new MyThread("第"+(i+1)+"个售票窗口");
    5. t1.start();
    6. }
    7. }
    8. }
    9. class MyThread extends Thread {
    10. private String name;
    11. private static int counter = 20;
    12. private final static String LOCK="lock1";
    13. public MyThread(String name) {
    14. this.name = name;
    15. }
    16. @Override
    17. public void run() {
    18. while (counter > 0) {
    19. try {
    20. sleep(100);// 模拟售票过程,加剧出错的可能性
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. }
    24. synchronized (LOCK) {
    25. if (counter > 0) {
    26. System.out.println(this.name + "售出第" + counter + "号票");
    27. // synchronized (LOCK) {
    28. counter--;
    29. // }
    30. } else {
    31. System.out.println("票已经售尽!");
    32. }
    33. }
    34. }
    35. }
    36. }

    锁的使用注意事项

    1:使用类锁,所以不管new了多少个对象,都可以得到互斥的效果

    1. public class A4 {
    2. public static void main(String[] args) {
    3. new Thread(() -> {
    4. for (int i = 0; i < 100; i++) {
    5. S4 ss = new S4();
    6. ss.pp1();
    7. }
    8. }).start();
    9. new Thread(() -> {
    10. for (int i = 0; i < 100; i++) {
    11. S4 ss = new S4();
    12. ss.pp1();
    13. }
    14. }).start();
    15. }
    16. }
    17. class S4 {
    18. public synchronized static void pp1() {
    19. System.out.println(Thread.currentThread() + "...begin...");
    20. try {
    21. Thread.sleep(100);
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. }
    25. System.out.println(Thread.currentThread() + "...end...");
    26. }
    27. public void pp2() {
    28. }
    29. }

    2:使用的是对象锁,所以只能new一个对象,才可以得到互斥的效果。如果创建多个则不能达到互斥的目的

    1. public class A41 {
    2. public static void main(String[] args) {
    3. S41 ss = new S41();
    4. new Thread(() -> {
    5. // S41 ss=new S41();
    6. for (int i = 0; i < 100; i++) {
    7. // S41 ss = new S41();
    8. ss.pp2();
    9. }
    10. }).start();
    11. new Thread(() -> {
    12. // S41 ss=new S41();
    13. for (int i = 0; i < 100; i++) {
    14. // S41 ss = new S41();
    15. ss.pp2();
    16. }
    17. }).start();
    18. }
    19. }
    20. class S41 {
    21. public synchronized static void pp1() {
    22. System.out.println(Thread.currentThread() + "pp1...begin...");
    23. try {
    24. Thread.sleep(100);
    25. } catch (InterruptedException e) {
    26. e.printStackTrace();
    27. }
    28. System.out.println(Thread.currentThread() + "pp1...end...");
    29. }
    30. public synchronized void pp2() {
    31. System.out.println(Thread.currentThread() + "pp2...begin...");
    32. try {
    33. Thread.sleep(100);
    34. } catch (InterruptedException e) {
    35. e.printStackTrace();
    36. }
    37. System.out.println(Thread.currentThread() + "pp2...end...");
    38. }
    39. }

    3:使用的是不同的锁,所以thread0和thread1不能达到互斥的目的

    1. public class A42 {
    2. public static void main(String[] args) {
    3. S42 ss = new S42();
    4. new Thread(() -> {
    5. for (int i = 0; i < 100; i++) {
    6. ss.pp2(); //非static -- 对象锁 ss
    7. }
    8. }).start();
    9. new Thread(() -> {
    10. for (int i = 0; i < 100; i++) {
    11. ss.pp1();//static --类锁 S42.class
    12. }
    13. }).start();
    14. }
    15. }
    16. class S42 {
    17. public synchronized static void pp1() {
    18. System.out.println(Thread.currentThread() + "pp1...begin...");
    19. try {
    20. Thread.sleep(100);
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. }
    24. System.out.println(Thread.currentThread() + "pp1...end...");
    25. }
    26. public synchronized void pp2() {
    27. System.out.println(Thread.currentThread() + "pp2...begin...");
    28. try {
    29. Thread.sleep(100);
    30. } catch (InterruptedException e) {
    31. e.printStackTrace();
    32. }
    33. System.out.println(Thread.currentThread() + "pp2...end...");
    34. }
    35. }

  • 相关阅读:
    【目标检测】49、YOLOF | 单层特征用的好就够啦!
    Mysql tinyint(1)与tinyint(4)的区别
    ElasticSearch - 基于 “黑马旅游” 案例,实现搜索框、分页、条件过滤、附近酒店、广告置顶功能
    外卖项目优化(三)前后端分离、接口文档、项目部署
    Elasticsearch集群部署
    EF7创建模型值生成篇
    javascript二维数组(3):指定数组元素的特定属性进行搜索
    【LeetCode-98】
    jsp344小区物业管理与疫情防控系统ssm
    使用RobustPCA 进行时间序列的异常检测
  • 原文地址:https://blog.csdn.net/m0_59749255/article/details/126490667