[Java multithreading] synchronized statement block

Mu Xin 2021-11-25 18:30:50
java multithreading synchronized statement block

Catalog

1. synchronized The disadvantages of the method

2. synchronized Use of synchronized code blocks

3. Using synchronization code block to solve the disadvantages of synchronization method

4. synchronized Synchronization between code blocks

5. Sync synchronized(this) The code block is locked to the current object

6. Use any object as a monitor

7. Refine validation 3 A conclusion


synchronized The method is to lock the current object , and synchronized A code block is a lock on an object .

1. synchronized The disadvantages of the method

In the use of synchronized Keyword to declare a method , Threads need to be queued for execution , Long running time .

2. synchronized Use of synchronized code blocks

When two concurrent threads access the same object object Medium synchronized(this) When synchronizing code , Only one thread can be executed in a period of time , Another thread must wait for the current thread to finish executing the block before it can execute .

Here is an example to illustrate synchronized Use of synchronized code blocks :

(1) ObjectService.java

public class ObjectService {
public void serviceMethod() {
try {
synchronized (this) {
System.out.println("begin time=" + System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("end end=" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

(2) ThreadA.java

public class ThreadA extends Thread {
private ObjectService service;
public ThreadA(ObjectService service) {
super();
this.service = service;
}
@Override
public void run() {
super.run();
service.serviceMethod();
}
}

(3) ThreadB.java

public class ThreadB extends Thread {
private ObjectService service;
public ThreadB(ObjectService service) {
super();
this.service = service;
}
@Override
public void run() {
super.run();
service.serviceMethod();
}
}

(4) Run.java

public class Run {
public static void main(String[] args) {
ObjectService service = new ObjectService();
ThreadA a = new ThreadA(service);
a.setName("a");
a.start();
ThreadB b = new ThreadB(service);
b.setName("b");
b.start();
}
}

Running results :

begin time=1633959635246
end end=1633959637258
begin time=1633959637258
end end=1633959639259

In the above experiment, although synchronized Synchronization code block , But the efficiency of implementation has not improved , The effect of execution is still synchronous .

3. Using synchronization code block to solve the disadvantages of synchronization method

To illustrate with an example :

(1)CommonUtils.java

public class CommonUtils {
public static long beginTime1;
public static long endTime1;
public static long beginTime2;
public static long endTime2;
}

(2) Task.java

public class Task {
private String getData1;
private String getData2;
public void doLongTimeTask() {
try {
System.out.println("begin task");
Thread.sleep(3000);
String privateGata1 = " Value returned from remote after long processing of task 1 threadName="
+ Thread.currentThread().getName();
String privateGata2 = " Value returned from remote after long processing of task 2 threadName="
+ Thread.currentThread().getName();
synchronized(this) {
getData1 = privateGata1;
getData2 = privateGata2;
}
System.out.println(getData1);
System.out.println(getData2);
System.out.println("end task");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

(3) MyThread1.java

public class MyThread1 extends Thread {
private Task task;
public MyThread1(Task task) {
super();
this.task = task;
}
@Override
public void run() {
super.run();
CommonUtils.beginTime1 = System.currentTimeMillis();
task.doLongTimeTask();
CommonUtils.endTime1 = System.currentTimeMillis();
}
}

(4) MyThread2.java

public class MyThread2 extends Thread {
private Task task;
public MyThread2(Task task) {
super();
this.task = task;
}
@Override
public void run() {
super.run();
CommonUtils.beginTime2 = System.currentTimeMillis();
task.doLongTimeTask();
CommonUtils.endTime2 = System.currentTimeMillis();
}
}

(5) Run.java

public class Run {
public static void main(String[] args) {
Task task = new Task();
MyThread1 thread1 = new MyThread1(task);
thread1.setName("A");
thread1.start();
MyThread2 thread2 = new MyThread2(task);
thread2.setName("B");
thread2.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long beginTime = Math.min(CommonUtils.beginTime1, CommonUtils.beginTime2);
long endTime = Math.max(CommonUtils.endTime1, CommonUtils.endTime2);
System.out.println(" Time consuming :" + ((endTime - beginTime) / 1000));
}
}

Running results :

begin task
begin task
Value returned from remote after long processing of task 1 threadName=B
Value returned from remote after long processing of task 2 threadName=A
Value returned from remote after long processing of task 1 threadName=A
Value returned from remote after long processing of task 2 threadName=A
end task
end task
Time consuming :3

According to the above experiment , When a thread accesses object One of the synchronized When synchronizing code blocks , Another thread can still access the object The non in the object synchronized(this) Synchronization code block .

be not in synchronized Block is asynchronous execution , stay synchronized Block is the synchronous execution .

4. synchronized Synchronization between code blocks

Using synchronization synchronized(this) One thing to note about code blocks is , When a thread accesses object One of the synchronized(this) When synchronizing code blocks , Other threads work on one at the same time object All the others in synchronized(this) Access to synchronized code blocks will block , This explanation synchronized The use of “ Object monitor ” It's a .

5. Sync synchronized(this) The code block is locked to the current object

and synchronized The method is the same ,synchronized(this) The code block also locks the current object .

6. Use any object as a monitor

Multiple threads call... With different names in the same object synchronized Synchronization method or synchronized(this) When synchronizing code blocks , The effect of the call is to execute in order , That's synchronous , Obstructed .

This explanation synchronized Synchronization method or synchronized(this) The synchronization code block consists of two functions .

(1)synchronized Synchronization method

  • 1) For others synchronized Synchronization method or synchronized(this) The synchronous code block call is blocked .
  • 2) Only one thread can execute at a time synchronized Code in the synchronization method .

(2)synchronized(this) Synchronization code block

  • 1) For others synchronized Synchronization method or synchronized(this) The synchronous code block call is blocked .
  • 2) Only one thread can execute at a time synchronized(this) Synchronize code in code .

In the previous study , Use synchronized(this) Format to synchronize code blocks , Actually Java Also supports the “ Any object ” As “ Object monitor ” To implement the synchronization function . This “ Any object ” Most of them are instance variables and method parameters , Use format as synchronized( Not this object ).

According to the front face synchronized(this) The summary of the function of synchronization code block shows that ,synchronized( Not this object ) There is only one function of format , namely  synchronized( Not this object x) Synchronization code block .

  • 1) Hold... In multiple threads “ Object monitor ” Under the premise of the same object , Only one thread can execute at a time synchronized( Not this object x) Synchronize the code in the code block .
  • 2) When held “ Object monitor ” On the premise that it is the object of consent , Only one thread can execute at a time synchronized( Not this object x) Synchronize the code in the code block .

Use synchronized( Not this object x) Synchronization code block format for synchronization operation , The object monitor must be the same object . If it's not the same object monitor , The result of running is asynchronous call , It will cross run .

Lock non this Objects have certain advantages : If there are many in a class synchronized Method , Although synchronization can be achieved at this time , But it's blocked , So it affects operational efficiency ; But if you use synchronous code block lock, it's not this object , be synchronized( Not this) The program in the code block is asynchronous to the synchronous method , Not with other locks this Synchronous method contention this lock , It can greatly improve the operation efficiency .

Synchronous code is placed in asynchronous synchronized Method , There is no guarantee that the execution of the thread calling the method is synchronized / Sequence , In other words, the order in which threads call methods is out of order , Although the order of execution in the synchronization block is synchronous , This is very easy to appear “ Dirty reading ” problem .

7. Refine validation 3 A conclusion

“synchronized( Not this object x)” The format is written in such a way that x The object itself acts as “ Object monitor ”, This leads to the following 3 A conclusion :

  • 1) When multiple threads execute at the same time synchronized(x){} Synchronization of code blocks .
  • 2) When other threads execute x Other in object synchronized The synchronization method is synchronous .
  • 3) When the thread executes x Object method synchronized(this) Code block also presents synchronization effect .

  But we need to pay attention : If other threads call without synchronized Keyword method , Or asynchronously .

版权声明
本文为[Mu Xin]所创,转载请带上原文链接,感谢
https://javamana.com/2021/11/20211109101849539v.html

  1. Flink Handling Function Real War II: processfunction class, Java thread interview subject
  2. Oracle SQL injection summary
  3. [Java data structure] you must master the classic example of linked list interview (with super detailed illustration and code)
  4. Record a java reference passing problem
  5. spring JTA 關於异常處理的時機問題
  6. Java - Set - Map (double file) - dija Rewriting, 2021 Java Developer's Performance Optimization
  7. Android入门教程 | OkHttp + Retrofit 取消请求的方法
  8. Java 8 Stream API and common methods, Java Junior Program interview
  9. Github 疯传!史上最强!BAT 大佬,2021年最新Java大厂面试笔试题分享
  10. git(3)Git 分支,zookeeper下载教程
  11. Java Backend Internet 500 questions d'entrevue moyennes et avancées (y compris les réponses), technologie de crochet Linux
  12. Entretien d'entretien d'usine Java post sprint de 100 jours - accumulation de jours et de mois, trois questions par jour [jour 12, fonction de principe de Zookeeper
  13. Tutoriel Java - reflection, tutoriel de téléchargement mongodb
  14. How to analyze several common key and hot issues in redis from multiple dimensions
  15. GIT (3) GIT Branch, Zookeeper Download tutoriel
  16. Tutoriel de démarrage Android | okhttp + Retrofit comment annuler une demande
  17. Design pattern [3.3] - Interpretation of cglib dynamic agent source code
  18. Share the actual operation of private collection project nodejs backend + Vue + Mysql to build a management system
  19. Springboot has 44 application initiators
  20. GitHub上霸榜久居不下的《Java面试突击宝典》,java图形用户界面设计基础
  21. GitHub上访问下载破百万的神仙文档《Java面试神技》看完我呆了,java面试问项目中遇到的问题
  22. GitHub上标星75k 超牛的《Java面试突击版,java高级工程师技能
  23. GitHub上标星2,java项目开发实训教程
  24. Docker development environment Preview
  25. JavaScript高級深入淺出:掌握 this 指向
  26. JavaScript Advanced Insight and outside: Mastering this direction
  27. Vue de l'application pratique de Javascript, drop drag Event
  28. docker 安装部署 Jenkins 2.322
  29. kafka安装
  30. 近九万字图文详解RabbitMQ
  31. Engaged in Java for one and a half years, how to break through yourself
  32. 输出9*9乘法表----java
  33. 判断一个数是不是素数-------java
  34. java项目,记录页面修改值,内部打“官司”用
  35. Docker installation Deployment Jenkins 2.322
  36. Comment porter un pantalon en hiver? Les petits hommes, les jambes épaisses et la largeur de l'entrejambe peuvent être vus. 3 techniques pour éviter la foudre
  37. MySQL下载和安装教程
  38. In depth analysis of rocketmq source code - message storage module
  39. Spring transaction management
  40. mysql恢复ibd数据,为何频频报错?
  41. [skills with annual salary of 60W] after working for 5 years, do you really understand netty and why to use it? (deep dry goods)
  42. Pourquoi MySQL récupère - t - il fréquemment les données ibd?
  43. Tutoriels de téléchargement et d'installation MySQL
  44. In IntelliJ idea, develop a fishing and reading plug-in
  45. Talk about how to integrate SPI with spring
  46. 重学Spring系列之Swagger2.0和Swagger3.0
  47. Hadoop05【命令操作】,Java400道面试题通关宝典助你进大厂
  48. Guava Cache缓存设计原理,java基础入门
  49. Gson:GitHub 标星 18K 的 JSON 解析器,Google 出品的 Java JSON 解析器
  50. gRPC学习之六:gRPC-Gateway集成swagger,java语言程序设计与数据结构进阶版
  51. Projet Java, enregistrer la valeur de modification de la page, utilisé pour les litiges internes
  52. Déterminer si un nombre est un nombre premier - - Java
  53. Sortie 9 * 9 tableau de multiplication - Java
  54. Plusieurs façons de réinitialiser le déplacement du Groupe de consommateurs Kafka
  55. GRPC Learning six: GRPC Gateway Integrated Swagger, Java language programming and data structure Advanced Edition
  56. python数据结构:数组、列表、栈、队列及实现
  57. Gson: json Parser for github Star 18k, Java json Parser from Google
  58. Principes de conception du cache Guava, Introduction à la base Java
  59. Un pantalon beige = élégant, blanc + haut de gamme, si beau cet hiver!
  60. Hadoop05 【 commande 】, Java 400 questions d'entrevue pour vous aider à entrer dans l'usine