[Java multithreading] static synchronized method and synchronized (class) code block

Mu Xin 2021-11-25 18:30:49
java multithreading static synchronized method

8. Static synchronization synchronized Methods and synchronized(class) Code block

keyword synchronized It can also be applied to static Statically , If you write like this , That's right now .java File corresponding Class Class to lock .*

Here is an example to illustrate the usage and effect .

(1) Service.java

public class Service {

synchronized public static void printA() {

try {

System.out.println(" The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Get into printA");
Thread.sleep(3000);
System.out.println("-- The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Leave printA");
} catch (InterruptedException e) {

e.printStackTrace();
}
}
synchronized public static void printB() {

System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Get into printB");
System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Leave printB");
}
}

(2) ThreadA.java

public class ThreadA extends Thread {

@Override
public void run() {

Service.printA();
}
}

(3) ThreadB.java

public class ThreadB extends Thread {

@Override
public void run() {

Service.printB();
}
}

(4) Run.java

public class Run {

public static void main(String[] args) {

ThreadA a = new ThreadA();
a.setName("A");
a.start();
ThreadB b = new ThreadB();
b.setName("B");
b.start();
}
}
 The thread name is :A stay 1634056855437 Get into printA
-- The thread name is :A stay 1634056858458 Leave printA
The thread name is :B stay 1634056858458 Get into printB
The thread name is :B stay 1634056858459 Leave printB

From the results of operation , Nothing special , It's all synchronous , And will be synchronized Keywords added to non static The effect of the method is the same . In fact, there are essential differences ,synchronized Keywords added to static Static method is to give Class Class lock , and synchronized Keywords added to non static Static methods are object locking .

To prove that it's not the same lock , We can verify it through the following experiments :

(1) Service.java

public class Service {

synchronized public static void printA() {

try {

System.out.println(" The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Get into printA");
Thread.sleep(3000);
System.out.println("---- The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Leave printA");
} catch (InterruptedException e) {

e.printStackTrace();
}
}
synchronized public static void printB() {

System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Get into printB");
System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Leave printB");
}
synchronized public void printC() {

System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Get into printC");
System.out.println("???? The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Leave printC");
}
}

(2) ThreadA.java

public class ThreadA extends Thread {

private Service service;
public ThreadA(Service service) {

super();
this.service = service;
}
@Override
public void run() {

service.printA();
}
}

(3) ThreadB.java

public class ThreadB extends Thread {

private Service service;
public ThreadB(Service service) {

super();
this.service = service;
}
@Override
public void run() {

service.printB();
}
}

(4) ThreadC.java

public class ThreadC extends Thread {

private Service service;
public ThreadC(Service service) {

super();
this.service = service;
}
@Override
public void run() {

service.printC();
}
}

(5) Run.java

public class Run {

public static void main(String[] args) {

Service service = new Service();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
ThreadC c = new ThreadC(service);
c.setName("C");
c.start();
}
}

Execution results :

 The thread name is :A stay 1634056663156 Get into printA
The thread name is :C stay 1634056663157 Get into printC
???? The thread name is :C stay 1634056663185 Leave printC
---- The thread name is :A stay 1634056666186 Leave printA
The thread name is :B stay 1634056666186 Get into printB
The thread name is :B stay 1634056666186 Leave printB

The experimental results show that : This experiment actually sets up two locks :

  • Object lock :printC Yes no static method , Constrained by object locks
  • Class lock :PrintA、PrintB It's a static method , All by the same Class constraint

The above can also be Service.java In code PrintB Change it to :

synchronized public void printB() {

System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Get into printB");
try {

Thread.sleep(5000);
} catch (InterruptedException e) {

e.printStackTrace();
}
System.out.println(" The thread name is :" + Thread.currentThread().getName() + " stay "
+ System.currentTimeMillis() + " Leave printB");
}

Rerun , give the result as follows :

 The thread name is :B stay 1634058460652 Get into printB
The thread name is :A stay 1634058460652 Get into printA
---- The thread name is :A stay 1634058461681 Leave printA
The thread name is :B stay 1634058465681 Leave printB
The thread name is :C stay 1634058465681 Get into printC
???? The thread name is :C stay 1634058465682 Leave printC

PrintB and PrintC Are non static , Belong to the same lock , therefore C Waiting B Release the lock when finished .

The reason for asynchrony is to hold different locks , One is object lock , The other is Class lock , and Class Locks work on all object instances of the class .

Sync synchronized(class) The function of code block is actually the same as synchronized static The method works the same .

With the following example ( Omit Thread file ) Verify that :

(1) Service.java

public class Service {

public static void printA() {

synchronized (Service.class) {

try {

System.out.println(" The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Get into printA");
Thread.sleep(3000);
System.out.println("---- The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Leave printA");
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
public static void printB() {

synchronized (Service.class) {

System.out.println(" The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Get into printB");
System.out.println("++++ The thread name is :" + Thread.currentThread().getName()
+ " stay " + System.currentTimeMillis() + " Leave printB");
}
}
}

(2)Run.java

public class Run {

public static void main(String[] args) {

Service service1 = new Service();
Service service2 = new Service();
ThreadA a = new ThreadA(service1);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service2);
b.setName("B");
b.start();
}
}

Execution results :

 The thread name is :A stay 1634098725887 Get into printA
---- The thread name is :A stay 1634098728911 Leave printA
The thread name is :B stay 1634098728911 Get into printB
++++ The thread name is :B stay 1634098728912 Leave printB
版权声明
本文为[Mu Xin]所创,转载请带上原文链接,感谢
https://javamana.com/2021/11/20211109101849536a.html

  1. Java经典面试题详解,突围金九银十面试季(附详细答案,mysql集群架构部署方案
  2. java整理,java高级特性编程及实战第一章
  3. java教程——反射,mongodb下载教程
  4. Java岗大厂面试百日冲刺 - 日积月累,每日三题【Day12,zookeeper原理作用
  5. Java后端互联网500道中高级面试题(含答案),linux钩子技术
  6. java8 Stream API及常用方法,java初级程序员面试
  7. java-集合-Map(双列)——迪迦重制版,2021Java开发社招面试解答之性能优化
  8. Flink处理函数实战之二:ProcessFunction类,java线程面试题目
  9. flex 布局详解,【Java面试题
  10. Linux basic command learning
  11. Why did docker lose to kubernetes? Docker employee readme!
  12. MySQL安装
  13. Elastic Search Aggregate Learning five: Problem Analysis of Uncertainty of sequencing results, Alibaba Java Performance Tuning Practical
  14. Installing, configuring, starting and accessing rabbitmq under Linux
  15. Oracle SQL injection summary
  16. Installation MySQL
  17. L'exposition à la photo d'essai sur la route i7 du nouveau vaisseau amiral de BMW Pure Electric a également été comparée à celle de Xiaopeng p7.
  18. spring JTA 关于异常处理的时机问题
  19. Le problème du temps de traitement des exceptions dans la JTA printanière
  20. Flink Handling Function Real War II: processfunction class, Java thread interview subject
  21. Oracle SQL injection summary
  22. [Java data structure] you must master the classic example of linked list interview (with super detailed illustration and code)
  23. Do you really know MySQL order by
  24. Record a java reference passing problem
  25. spring JTA 關於异常處理的時機問題
  26. Java - Set - Map (double file) - dija Rewriting, 2021 Java Developer's Performance Optimization
  27. Android入门教程 | OkHttp + Retrofit 取消请求的方法
  28. Java 8 Stream API and common methods, Java Junior Program interview
  29. Github 疯传!史上最强!BAT 大佬,2021年最新Java大厂面试笔试题分享
  30. git(3)Git 分支,zookeeper下载教程
  31. Java Backend Internet 500 questions d'entrevue moyennes et avancées (y compris les réponses), technologie de crochet Linux
  32. 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
  33. Tutoriel Java - reflection, tutoriel de téléchargement mongodb
  34. How to analyze several common key and hot issues in redis from multiple dimensions
  35. GIT (3) GIT Branch, Zookeeper Download tutoriel
  36. Tutoriel de démarrage Android | okhttp + Retrofit comment annuler une demande
  37. Design pattern [3.3] - Interpretation of cglib dynamic agent source code
  38. Share the actual operation of private collection project nodejs backend + Vue + Mysql to build a management system
  39. Springboot has 44 application initiators
  40. GitHub上霸榜久居不下的《Java面试突击宝典》,java图形用户界面设计基础
  41. GitHub上访问下载破百万的神仙文档《Java面试神技》看完我呆了,java面试问项目中遇到的问题
  42. GitHub上标星75k 超牛的《Java面试突击版,java高级工程师技能
  43. GitHub上标星2,java项目开发实训教程
  44. Docker development environment Preview
  45. JavaScript高級深入淺出:掌握 this 指向
  46. JavaScript Advanced Insight and outside: Mastering this direction
  47. Vue de l'application pratique de Javascript, drop drag Event
  48. docker 安装部署 Jenkins 2.322
  49. kafka安装
  50. 近九万字图文详解RabbitMQ
  51. Engaged in Java for one and a half years, how to break through yourself
  52. 输出9*9乘法表----java
  53. 判断一个数是不是素数-------java
  54. java项目,记录页面修改值,内部打“官司”用
  55. Docker installation Deployment Jenkins 2.322
  56. 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
  57. MySQL下载和安装教程
  58. In depth analysis of rocketmq source code - message storage module
  59. Spring transaction management
  60. mysql恢复ibd数据,为何频频报错?